Cocos2d-x Physics 2 - Hello Physics World

在层的头文件定义一个变量和一个方法

 

class HelloWorld : public cocos2d::Layer

 

{

 

public:

    ... 

    //physics world

    cocos2d::PhysicsWorld *m_physicsWorld;

    void setPhysicsWorld(cocos2d::PhysicsWorld *physicsWorld){m_physicsWorld = physicsWorld;};

 

};

 

 

创建一个具有物理特性的场景

Scene* HelloWorld::createScene()

{

    // 创建一个具有物理特性的场景

    auto scene = Scene::createWithPhysics();

    //开启物理引擎的调试模式

    scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);

    

    // 'layer' is an autorelease object

    auto layer = HelloWorld::create();

    

    Size visibleSize = Director::getInstance()->getVisibleSize();

    

    //创建一个矩形边界

    auto nodeBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3);

    

    auto node = Node::create();

    node->setPhysicsBody(nodeBody);//设置刚体

    node->setPosition(visibleSize.width/2, visibleSize.height/2);

    scene->addChild(node);

 

    //将物理世界传递给层

    layer->setPhysicsWorld(scene->getPhysicsWorld()); 

    // add layer as a child to scene

    scene->addChild(layer);

 

    // return the scene

    return scene;

}

 

 

 

物理世界默认的重力是 vect(0, -98);

可以通过setGravity方法更改重力

scene->getPhysicsWorld()->setGravity(Vec2(0, -500));

 

createEdgeBox方法有三个参数, 依次是:

1. 矩形区域的大小

2. 设置材质

3. 边线宽度

 

PHYSICSBODY_MATERIAL_DEFAULT 是一个预定义的PhysicsMaterial类, 预设值分别是

Density 密度 = 0.0f

Restitution 恢复力(弹力) = 0.5f

Friction 摩擦力 = 0.5f

 

 

运行结果可以看到屏幕四周有一个红色的边框

NewImage

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2014-11-08 15:47  <懒洋洋>  阅读(297)  评论(0编辑  收藏  举报