cocos2d-x lua 3D模块学习(3)----3D物理引擎

cocos2d-x 3.X封装的是Bullet的物理引擎

使用也是很简单,精灵绑定刚体,设置为组件,就可以一起运动了,很方便

首先场景必须是物理世界的,这在2d还是3d中都是一样的,不然会黑屏哦

    local pScene = cc.Scene:createWithPhysics()
    if cc.Director:getInstance():getRunningScene() then
        cc.Director:getInstance():replaceScene(pScene)
    else
        cc.Director:getInstance():runWithScene(pScene)
    end
    self._physicsScene = cc.Director:getInstance():getRunningScene()
    local winSize = cc.Director:getInstance():getWinSize()
    local physics3DWorld = self._physicsScene:getPhysics3DWorld()
为了方便调试,我们将物理的线框给显示出来。
physics3DWorld:setDebugDrawEnable(isDebug)

这样3D物理系统的初始化就已经做好了

创建刚体

首先,我们需要定义一个刚体的描述类型的对象,这个对象包括了该刚体的形状,以及质量,还有局部变换等信息,一般的,我们只定义刚体的质量以及形状就足够了。

                local rbDes = { }
                rbDes.disableSleep = true
                rbDes.mass = 1.0
                rbDes.shape = cc.Physics3DShape:createSphere(ball:getContentSize().width / 2 / 100)
                local rigidBody = cc.Physics3DRigidBody:create(rbDes)
                local component = cc.Physics3DComponent:create(rigidBody)
                Texture3D = cc.PhysicsSprite3D:create("gameBilliards/3d/ball.c3b", rbDes)
                Texture3D:setTexture("gameBilliards/3d_ball/" .. i .. ".png")
                Texture3D:setPosition(cc.p(ball:getContentSize().width / 2, ball:getContentSize().height / 2))
                Texture3D:setTag(8)
                Texture3D:setScale(s3d_Width * 2 /(ball:getContentSize().width / 2))
                Texture3D:setCameraMask(cc.CameraFlag.USER2)
                self:addChild(Texture3D)
                

注意这里,如果是静态物体,rbDes.mass必须不等于0,0是默认值,是静态刚体,是不会动的,很坑爹

cc.PhysicsSprite3D:create是创建3d物理特性的精灵

rbDes.disableSleep = true是刚体的网格变为红色,不知道效果是什么,默认是绿色的

还有一种创建方法是绑定刚体在sprite3D上,再绑定组件。

local rbDes = {}
    rbDes.disableSleep = true
    --create box
    local sprite = cc.Sprite3D:create("Sprite3DTest/orc.c3b")
    rbDes.mass = 10.0
    rbDes.shape = cc.Physics3DShape:createBox(cc.vec3(5.0, 5.0, 5.0))
    local rigidBody = cc.Physics3DRigidBody:create(rbDes)

    local quat = cc.quaternion_createFromAxisAngle(cc.vec3(0, 1, 0), math.pi)
    local component = cc.Physics3DComponent:create(rigidBody, cc.vec3(0.0, -3.0, 0.0), quat)

    sprite:addComponent(component)
    self:addChild(sprite)
    sprite:setCameraMask(cc.CameraFlag.USER1)
    sprite:setScale(0.4)
    sprite:setPosition3D(cc.vec3(-20.0, 5.0, 0.0))
    --sync node position to physics
    component:syncNodeToPhysics()
    --physics controlled, we will not set position for it, so we can skip sync node position to physics
    component:setSyncFlag(cc.Physics3DComponent.PhysicsSyncFlag.PHYSICS_TO_NODE)

syncNodeToPhysics是同步节点到物理世界去

扫描二维码关注公众号,回复: 873697 查看本文章

Physics3DComponent用以将Node的数据和刚体的数据互相关联,同时可以指定其相对于其父节点的一些偏移设置,其设置的方法,在上一篇教程介绍PhysicsSprite3D也有提到过,在这里,只需要将其加入到Sprite3D下就可以了。

狩猎不深,有什么想到的再补充吧




猜你喜欢

转载自blog.csdn.net/qq_37508511/article/details/80335727