cocos2dx+lua 第一次使用物理引擎

10 篇文章 0 订阅

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

效果:点击屏幕则在点击处生成一个具有向上初速度的足球,足球在重力下自由下落,最终停在边界上。不同的小球之间、小球与边界之间都会产生碰撞。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值