MainScene.lua
local MainScene = class("MainScene", cc.load("mvc").ViewBase)
local FootBallGame = import(".FootBallGame")
function MainScene:onCreate()
-- add playbutton
local playButton = cc.MenuItemImage:create("button_play.png", "button_playclicked.png")
:onClicked(function()
--local scene = self:getApp():getSceneByName("PlayScene")
local scene = FootBallGame:create()
local transition = cc.TransitionSlideInR:create(0.5, scene)
cc.Director:getInstance():replaceScene(transition)
end)
cc.Menu:create(playButton)
:move(cc.p(display.cx, display.cy - 100))
:addTo(self)
end
return MainScene
FootBallGame.lua
--創建普通Scene
--local FootBallGame = class("FootBallGame", function()
-- return cc.Scene:create()
--end)
--local FootBallGame = class("FootBallGame", cc.Scene)
--創建帶物理世界的Scene
local FootBallGame = class("FootBallGame", function()
return cc.Scene:createWithPhysics()
end)
function FootBallGame:ctor()
-- add background image
display.newSprite("bg_dayLong.png")
:move(display.center)
:addTo(self)
--設置重力
self:getPhysicsWorld():setGravity(cc.vertex2F(0,-980))
--創建物理世界邊界
local edge = cc.Node:create()
--創建一個不受重力影響的矩形邊界並綁定到Node結點上
edge:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.Director:getInstance():getVisibleSize()))
edge:setPosition(display.center)
self:addChild(edge)
--註冊鼠標監聽事件,點擊觸發onTouch函數
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(function(touch, event)
self:onTouch(touch, event)
end,cc.Handler.EVENT_TOUCH_BEGAN)
self:getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, self)
self._touchListener = listener
end
--定義callback函數
function FootBallGame:onTouch(touch,event)
local location = touch:getLocation()
local x,y = location.x,location.y
local football = cc.Sprite:create("football.png")
local size = football:getContentSize()
football:setPosition(x,y)
--創建一個圓形剛體綁定到Sprite上
football:setPhysicsBody(cc.PhysicsBody:createCircle(size.width/2))
--給剛體設置初速度
football:getPhysicsBody():setVelocity(cc.vertex2F(0,300))
self:addChild(football)
return true
end
return FootBallGame
效果:點擊屏幕則在點擊處生成一個具有向上初速度的足球,足球在重力下自由下落,最終停在邊界上。不同的小球之間、小球與邊界之間都會產生碰撞。