下面是main.lua文件的完整代码,单击屏幕任意一点会创建一个精灵,精灵之间相互碰撞后产生回调事件。
local MainScene = class ("MainScene",function()
return display.newScene("MainScene",{physics = 2})
end)
function MainScene:ctor()
self:getPhysicsWorld():setGravity(cc.p(0,-100)) --重力
self:getPhysicsWorld():setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)
local size = display.size
local body = cc.PhysicsBody:createEdgeBox(size,cc.PHYSICSBODY_MATERIAL_DEFAULT,2)
local edgeNode = display.newNode()
edgeNode:setPosition(size.width/2,size.height/2)
edgeNode:setPhysicsBody(body)
self:addChild(edgeNode)
--监听碰撞
local function onContactBegin(contact)
local tag = contact:getShapeA():getBody():getNode():getTag()
-- print(tag) --碰撞后的回调事件
return true
end
local contactListener = cc.EventListenerPhysicsContact:create()
contactListener:registerScriptHandler(onContactBegin,cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
eventDispatcher:addEventListenerWithFixedPriority(contactListener,1)
self:getPhysicsWorld():setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)
local function onTouchBegan( touch, event )
return true
end
local function onTouchEnded( touch, event )
local location = touch:getLocation() --获取鼠标的位置
local event_x = location["x"] or 0
local event_y = location["y"] or 0
self:addSprite(event_x,event_y)
end
local function onTouchMoved(touch, event)
end
local listener1 = cc.EventListenerTouchOneByOne:create() --创建一个单点事件监听
listener1:setSwallowTouches(false) --是否向下传递
listener1:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
listener1:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )
listener1:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener1, self) --分发监听事件
end
function MainScene:addSprite(x,y)
local oneSprite = display.newSprite("game/basketball/image/basketball.png")
-- local oneBody = cc.PhysicsBody:createBox(oneSprite:getContentSize(),cc.PHYSICSBODY_MATERIAL_DEFAULT,cc.p(0,0)) --矩形刚体
local oneBody = cc.PhysicsBody:createCircle(25,cc.PHYSICSBODY_MATERIAL_DEFAULT,cc.p(0,0)) --圆形刚体
oneBody:setContactTestBitmask(0xFFFFFFFF)
oneBody:applyImpulse(cc.p(0,10000))
oneSprite:setPhysicsBody(oneBody)
oneSprite:setPosition(x,y)
oneSprite:setTag(101)
self:addChild(oneSprite)
end
function MainScene:showWithScene(transition, time, more)
self:setVisible(true)
local scene = self
display.runScene(scene, transition, time, more)
return self
end
return MainScene
效果图如下
|
请发表评论