Cocos2d-x box2d Demo Annotations

Source: Internet
Author: User
Tags addchild

Hard work and perseverance.

Core Concepts

There are some main objects in the box2d, here we make a brief definition, and in the subsequent documents there will be more specific description.

Rigid body (rigid body)

10 Yuan The hard matter, the distance between the two points above it is completely unchanged.

They are as hard as diamonds.

In a later discussion, we replace a rigid body with an object (body).

Shapes (Shape)

A 2D collision geometry (collision geometry) that is rigidly attached to an object (body).

The shape has the material properties of friction (friction) and recovery (restitution).

Constraint (constraint)

A constraint (constraint) is a physical connection that eliminates the freedom of an object. In 2D, an object has 3 degrees of freedom. Suppose we nail an object to the wall (like a pendulum), we constrain it to the wall. In this way, the object can only rotate around the nail, so this constraint eliminates 2 degrees of freedom.

Contact constraints (Contacts constraint)

A special constraint that prevents the penetration of a rigid body and is used to simulate friction (friction) and recovery (restitution). You never have to create a contact constraint, they will be created by box2d on their own initiative.

Joints (joint)

It is a constraint used to fasten two or more objects together. The types of joints supported by box2d are: rotation, prism, distance and so on.

Joints can support limits (limits) and motors (motors).

Joint limit (joint limit)

A joint limit (joint limit) limits the range of motion of a joint. For example, the human elbow can only do a certain range of angle movement.

Joint Motors (joint motor)

A joint motor can drive the connected object according to the degree of freedom of the joint. For example, you can use a motor to drive the rotation of an elbow.

Worlds (World)

A physical world is a collection of objects, shapes, and constraints interacting. BOX2D supports the creation of multiple worlds, but this is generally not necessary .

helloworldscene.cpp//box2d////Created by Xiangzi on 14-6-23.//Copyright __mycompanyname__ 2014. All rights reserved.//#include "HelloWorldScene.h"//unit: The distance in box2d is in meters, the mass is in kilograms, and the time is in seconds. The width and height values of the screen are divided by a constant named Ptm_ratio, which converts the pixel value to the length measured in meters. #define Ptm_ratio//ptm_ratio is used to define 32 pixels equivalent to 1 meters in a box2d world.

enum {Ktagparentnode = 1,}; Physicssprite::P hysicssprite (): M_pbody (NULL) {}void physicssprite::setphysicsbody (b2body * body) {m_pbody = body;} Override the IsDirty method and return Yes to draw the Physicssprite Wizard again after the update call for each layer.

BOOL Physicssprite::isdirty (void) {return true;} /* Rewrite the wizard's matrix transform method Nodetoparenttransform, which is provided by the template for this implementation. Can change the position and angle of the sprite. We will see that in the update function, the box2d step method is called, which calculates the new position and angle of each rigid body based on the elapsed time, and is then used here to finally achieve the purpose of the sprite movement rotation. */ccaffinetransform physicssprite::nodetoparenttransform (void) {b2vec2 pos = m_pbody->getposition (); float x = pos.x * ptm_ratio; Float y = pos.y * ptm_ratio; if (Isignoreanchorpointforposition ()) {x + = m_obanchorpointinpoints.x; Y + = M_obanchorpointinpoints.y; }//make matrix float radians = M_pbody->getangle (); float c = COSF (radians); float s = sinf (radians); if (! m_obanchorpointinpoints.equals (Ccpointzero)) {x + = c*-m_obanchorpointinpoints.x +-s*-m_obanchorpointinpoint S.y; Y + = s*-m_obanchorpointinpoints.x + c*-m_obanchorpointinpoints.y; }//Rot, Translate Matrix m_stransform = Ccaffinetransformmake (c, S,-S, c, X, y); return m_stransform;} Helloworld::helloworld () {settouchenabled (tRue); Setaccelerometerenabled (TRUE); Ccsize s = ccdirector::shareddirector ()->getwinsize (); Init physics This->initphysics (); Ccspritebatchnode *parent = ccspritebatchnode::create ("Blocks.png", 100); M_pspritetexture = Parent->gettexture (); AddChild (parent, 0, Ktagparentnode); Addnewspriteatposition (CCP (S.WIDTH/2, S.HEIGHT/2)); Cclabelttf *label = cclabelttf::create ("Tap Screen", "Marker Felt", 32); AddChild (label, 0); Label->setcolor (CCC3 (0,0,255)); Label->setposition (CCP (S.WIDTH/2, s.height-50)); Scheduleupdate ();} Helloworld::~helloworld () {delete world; World = NULL; }void Helloworld::initphysics () {ccsize s = ccdirector::shareddirector ()->getwinsize (); B2VEC2 Gravity; Gravity. Set (0.0f, -10.0f); Initialize world = new B2world (Gravity) for box2d worlds; /* Dynamic rigid body with "sleep": when the force applied to a rigid body is less than the critical value, the rigidbody will go into "sleep" state after a period of time. Other words. Assuming that a rigid body moves or rotates very slowly or does not move at all, the physics engine will mark it as "asleep" and no longer exert force on it until the new force is applied to the rigidbody to move or rotate again. By puttingSome rigid bodies are labeled "Sleep", and the physical engine can save a lot of time. You should set the setallowsleeping variable to true unless all the dynamic rigid bodies in your game are in continuous motion. */World->setallowsleeping (TRUE); Set Test continuous Collision world->setcontinuousphysics (true); 1. Create a body definition structure. The initial property used to specify the body. For example, position or speed. B2bodydef Groundbodydef; GroundBodyDef.position.Set (0, 0); 2. Call the World object to create a body object b2body* groundbody = World->createbody (&groundbodydef); 3. Define a shape for the body object that specifies the geometry of the object you want to emulate. B2edgeshape Groundbox; 4. Create a fixture definition. At the same time set a property that was created before the shape is fixture. and set other properties, such as mass or friction.

Bottom Groundbox.set (b2vec2 (0,0), B2VEC2 (s.width/ptm_ratio,0)); Groundbody->createfixture (&groundbox,0); Top Groundbox.set (B2VEC2 (0,s.height/ptm_ratio), B2VEC2 (S.width/ptm_ratio,s.height/ptm_ratio)); Groundbody->createfixture (&groundbox,0); Left Groundbox.set (B2VEC2 (0,s.height/ptm_ratio), B2VEC2 (0,0)); Groundbody->createfixture (&groundbox,0); Right Groundbox.set (B2VEC2 (S.width/ptm_ratio,s.height/ptm_ratio), B2VEC2 (s.width/ptm_ratio,0)); Groundbody->createfixture (&groundbox,0);} void HelloWorld::d raw () {/////IMPORTANT://This is only for debug purposes//It's recommend to disable it Cclayer::d Raw (); Ccglenablevertexattribs (kccvertexattribflag_position); Kmglpushmatrix (); World->drawdebugdata (); Kmglpopmatrix ();} void Helloworld::addnewspriteatposition (Ccpoint p) {ccnode* parent = Getchildbytag (Ktagparentnode); There is a 64x64 sprite table with 4 different 32x32 images, just a random selection of one of these images. int idx = (Ccrandom_0_1 () >. 5?

0:1); int idy = (ccrandom_0_1 () >. 5?

0:1); Physicssprite *sprite = new Physicssprite (); Sprite->initwithtexture (M_pspritetexture, Ccrectmake (+ * idx,32 * idy,32,32)); Sprite->autorelease (); Parent->addchild (sprite); Sprite->setposition (Ccpointmake (p.x, p.y)); 1. Create a body definition structure. The initial property used to specify the body. For example, position or speed.

B2bodydef Bodydef; Bodydef.type = B2_dynamicbody; BodyDef.position.Set (P.x/ptm_ratio, p.y/ptm_ratio); 2. Call the World object to create a body object b2body *body = World->createbody (&bodydef); 3. Define a shape for the body object. Used to specify the geometry of the object you want to emulate. B2polygonshape Dynamicbox; Dynamicbox.setasbox (. 5f,. 5f);//these is mid points for our 1m box/*4. Create a fixture definition, at the same time set a genus that was created before the shape is fixture Of and set other properties, such as mass or friction. Meaning of density,friction and restitution: density is the mass (density) of the unit volume. So. The greater the density of an object, the more mass it has, and the more difficult it will be to move. Friction is friction.

Its range is 0-1.0. 0 means no friction, 1 represents the maximum friction. Almost the friction of moving. Restitution recovery force.

Its range is also 0 to 1.0.0 means that the object does not bounce after the collision, and 1 means a completely elastic collision. Will bounce at the same speed. */B2fixturedef Fixturedef; Fixturedef.shape = &dynamicBox; fixturedef.density = 1.0f; Density fixturedef.friction = 0.3f; Friction Body->createfixture (&FIXTUREDEF); Call the Sprite's setphysicsbody to set the body for a sprite. Sprite->setphysicsbody (body);} Updates the position and rotation information of each rigid body associated with the Sprite void Helloworld::update (float dt) {int velocityiterations = 8; int positioniterations = 1; /* BOX2D's world is animated by calling the step method on a regular basis. The step method requires a three number of parameters.

The first one is Timestep, which will tell box2d how long it has been since the last update, which directly affects how long it takes to move in this step. It is not recommended to use DT as the value of Timestep. As the DT floats up and down, the rigid body cannot move at the same speed. The second and third parameters are the number of iterations. They are used to determine the exact degree of physical simulations. It also determines the time required to calculate the movement of a rigid body. */World->step (0.015, velocityiterations, positioniterations); In the world of physics traverse each rigid body for (b2body* B = world->getbodylist (); b; b = B->getnext ()) {if (b->getuse RData ()! = NULL) {//synchronize The atlassprites position and rotation with the corresponding body ccsprite* myactor = (ccsprite*) b->getuserdata (); Myactor->setposition (Ccpointmake (B->getposition (). x * Ptm_ratio, B->getposition (). Y * PTM_RATIO)); Unit conversion m-pixel myactor->setrotation (-1 * cc_radians_to_degrees (B->getangle ())); Unit conversion radian-angle}}}void helloworld::cctouchesended (ccset* touches, ccevent* event) {Ccsetiterator it; Cctouch* Touch; for (it = Touches->begin (); It! = Touches->end (); it++) {touch =(cctouch*) (*it); if (!touch) break; Ccpoint location = Touch->getlocation (); Addnewspriteatposition (location); }}ccscene* Helloworld::scene () {Ccscene *scene = Ccscene::create (); cclayer* layer = new HelloWorld (); Scene->addchild (layer); Layer->release (); return scene;}

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Cocos2d-x box2d Demo Annotations

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: 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.