The header file at the layer defines a variable and a method.
?
Class HelloWorld: public cocos2d: Layer
?
{
?
Public:
? ? ...?
? ?? // Physics world
? ? Cocos2d: PhysicsWorld * m_physicsWorld;
? ? Void setPhysicsWorld (cocos2d: PhysicsWorld * physicsWorld) {m_physicsWorld = physicsWorld ;};
?
};
?
?
Create a scenario with physical characteristics
Scene * HelloWorld: createScene ()
{
? ? // Create a scenario with physical characteristics
? ? Auto scene = Scene: createWithPhysics ();
? ? // Enable the debugging mode of the physical engine
? ? Scene-> getPhysicsWorld ()-> setDebugDrawMask (PhysicsWorld: DEBUGDRAW_ALL );
?? ?
? ? // 'Player' is an autorelisted object
? ? Auto layer = HelloWorld: create ();
?? ?
? ? Size visibleSize = Director: getInstance ()-> getVisibleSize ();
?? ?
? ? // Create a rectangle boundary
? ? Auto nodeBody = PhysicsBody: createEdgeBox (visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3 );
?? ?
? ? Auto node = Node: create ();
? ? Node-> setPhysicsBody (nodeBody); // you can specify a rigid body.
? ? Node-> setPosition (visibleSize. width/2, visibleSize. height/2 );
? ? Scene-> addChild (node );
?
? ?? // Pass the physical world to the layer
? ? Layer-> setPhysicsWorld (scene-> getPhysicsWorld ());?
? ? // Add layer as a child to scene
? ? Scene-> addChild (layer );
?
? ? // Return the scene
? ? Return scene;
}
?
?
?
The default gravity in the physical world is vect (0,-98 );
You can use the setGravity method to change the gravity.
Scene-> getPhysicsWorld ()-> setGravity (Vec2 (0,-500 ));
?
The createEdgeBox method has three parameters:
1. Rectangular area size
2. Set Materials
3. Edge width
?
PHYSICSBODY_MATERIAL_DEFAULT is a predefined PhysicsMaterial class. The default values are
Density = 0.0f
Restitution recovery force (elasticity) = 0.5f
Friction = 0.5f
?
?
The running result shows a red border around the screen.
?
?
?
?
?
?
?
?
?
?
?
?
?
?
Cocos2d-x Physics 2-Hello Physics World