cocos的物理碰撞系統使用方式,適應用2D,3D捕魚

首先設置整體場景的物體世界

	self =display.newScene("MainScene",{physics=true})--創建物體世界
    local physicsWord = self:getPhysicsWorld()
	physicsWord:setGravity(cc.p(0, 0))
	physicsWord:setUpdateRate(3);--設置頻率
	if physicsWord ~=nil then
		physicsWord:setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)
	end
	 local function onContactBegin(contact)--碰撞後的回調
        local a = contact:getShapeA():getBody()
        local bulletNode =nil 
        local b = contact:getShapeB():getBody()
        local fishNode =  nil 
		local bulletIsMe= 0
		if a:getTag()>=0 then
			bulletNode =a:getNode(); 
			bulletIsMe=a:getTag();
			fishNode =  b:getNode(); 
			
		else
			bulletNode =b:getNode(); 
			bulletIsMe=b:getTag();
			fishNode =  a:getNode();
		end
		if bulletNode~=nil and fishNode~=nil then 
       		self.eventDispatcher = self:getEventDispatcher() 
			if(bulletIsMe>0) then
				local event = cc.EventCustom:new(EventMsgId.MSG_FISH_HIT)
				event.data = 
                {fishID=fishNode:getTag(),bulletID=bulletNode:getTag(),isMe=bulletIsMe}
				self.eventDispatcher:dispatchEvent(event)
			end
			
		end
			
        return true
      end
	local contactListener = cc.EventListenerPhysicsContact:create()--設置碰撞回調
    contactListener:registerScriptHandler(onContactBegin, 
    cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
    local eventDispatcher = self:getEventDispatcher()
    eventDispatcher:addEventListenerWithSceneGraphPriority(contactListener, self)
	

  然後,設置碰撞物體的body設置

物體1:   
    self._body =cc.PhysicsBody:createBox(cc.size(60.0, 60))
	self._body:setCategoryBitmask(1)    -- 0001掩碼
    self._body:setContactTestBitmask(2) -- 0011消息
    self._body:setCollisionBitmask(0)   -- 0010碰撞
    self._body:setTag(1)
    self.m_pArmature:setPhysicsBody(self._body);
物體2:
    self._bodySprite:setScale(_sx, _sy)
    self._bodySprite:setPosition(-1000,-1000)
    self._bodySprite:setRotation(_fishRotate)	
	self._bodySprite:setTag(self.uid)
	_mainUILayer:addChild(self._bodySprite)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章