Getting started with Cocos2d-x series eight Box2d

Source: Internet
Author: User

Since there is a cocos2d-x, why Box2d it, because the cocos2d-x as an image engine, just used to display the image, the image can be any coincidence between, If You Want To Do similar physics collision and other motion effect, box2d is used to simulate objects in the physical world;

This article describes how to create dynamic objects, static objects, floating objects, and their binding to images;

The following example shows how to create three objects;

The first thing to note is that in Box2d, the unit is meter rather than pixel. Therefore, you need to scale proportionally during position conversion. In Box2d, the ideal distance is 10 meters, so you have to scale the screen width and height proportionally (for example, the RADIO defined in the following example is the proportion I defined );

HelloWorldScene. cpp

# Include "HelloWorldScene. h "# define RADIO 80Scene * HelloWorld: createScene () {// 'Scene 'is an autorelease object auto scene = scene: create (); // 'player' is an autorelease object auto layer = HelloWorld: create (); // add layer as a child to scene-> addChild (layer ); // return the scene return scene;} // on "init" you need to initialize your instancebool HelloWorld: init () {///////////////////// /// // 1. super init first if (! Layer: init () {return false;} world = new b2World (b2Vec2 (0,-10); // the acceleration in the x direction is 0, the acceleration in the y direction is 10 world-> SetContactListener (this); // Add an object impact event listener addGround (); addRect (); scheduleUpdate (); // start to execute handler, the method return true when the first update is executed;} void HelloWorld: update (float dt) {world-> Step (dt, 8, 3 ); // The three parameters indicate the time interval between the current frame and the last frame respectively. Since the update method is executed once every frame of the program, the frame rate dt is directly introduced;
// The second parameter indicates the number of speed iterations. The official recommendation is 8;
// The third parameter indicates the number of location iterations. The official recommendation is 3; Sprite * s; for (b2Body * B = world-> GetBodyList (); B; B = B-> GetNext () {if (B-> GetUserData () {s = (Sprite *) B-> GetUserData (); s-> setPosition (B-> GetPosition (). x * RADIO, B-> GetPosition (). y * RADIO); // update the Object Location} void HelloWorld: BeginContact (b2Contact * contact) {// The callback interface log ("contact? "); If (contact-> GetFixtureA ()-> GetBody () = ground | contact-> GetFixtureB ()-> GetBody () = ground) {log ("yeah, contacted! ") ;}} Void HelloWorld: addRect () {// Add a dynamic Rect and bind it to a Sprite; b2BodyDef; def. type = b2_dynamicBody; // specify the type as a dynamic object @ 1 def. position = b2Vec2 (3, 1); // start position (3, 1) def. linearVelocity = b2Vec2 (); // (initial) linear speed. If the type is floating, the object will not perform constant motion in this direction. If it is dynamic, the preset acceleration is used for Speed Conversion, b2PolygonShape shape, and shape. setAsBox (0.5, 0.5); // set a Shape. The two parameters indicate the size of the left half side and the upper half side respectively. Therefore, here two 0.5 actually defines a 1x1 block b2FixtureDef fixtureDef; fixtureDef. density = 1; // specify the object density fixtureDef. friction = 0.3; // specifies the friction of the object fixtureDef. shape = & shape; // specify the shape b2Body * body = world-> CreateBody (& def); auto s = Sprite: create (); s-> setTextureRect (Rect (0, 0, 30, 30); // set addChild (s) for the area displayed by sprite; body-> CreateFixture (& fixtureDef ); // After FixtureDef is set, there will be a collision between the two objects. If there is no collision effect, the object will keep moving in a certain direction; body-> SetUserData (s); // binds a Sprite to an object} void HelloWorld: addGround () {// Add a static object and add it to the bottom of the object in, blocks The freely dropped object b2BodyDef; def created in the previous step. type = b2_staticBody; def. position = b2Vec2 (0, 0); b2PolygonShape shape; shape. setAsBox (400/RADIO, 10/RADIO); // set the object size. ground = world-> CreateBody (& def); auto s = Sprite: create (); s-> setTextureRect (Rect (,); b2FixtureDef fixtureDef; fixtureDef. density = 0.5; fixtureDef. friction = 0.3; fixtureDef. shape = & shape; addChild (s); ground-> CreateFixture (& fixtureDef); ground-> SetUserData (& def );}

HelloWorldScene. h

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include <Box2D/Box2D.h>USING_NS_CC;class HelloWorld : public Layer,public b2ContactListener{private :    b2World *world;    b2Body *ground;public:    // there's no 'id' in cpp, so we recommend returning the class instance pointer    static cocos2d::Scene* createScene();    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone    virtual bool init();      // a selector callback    void menuCloseCallback(cocos2d::Ref* pSender);    // implement the "static create()" method manually    CREATE_FUNC(HelloWorld);    virtual void update(float dt);    void addRect();    void addGround();    /// Called when two fixtures begin to touch.    virtual void BeginContact(b2Contact* contact) ;};#endif // __HELLOWORLD_SCENE_H__

@ 1: There are three types of types:

  • B2_staticBody (static)
  • B2_kinematicBody (floating, movable, but constant speed)
  • B2_dynamicBody (dynamic, speed changing)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.