IOS-Cocos2d game development 11: Using box2d physical system and adding box2d physical system lib package in the cocos2d framework

Source: Internet
Author: User

Li huaming himiOriginal, reprinted must be explicitly noted:
Reprinted from[Heimi gamedev block]Link: http://www.himigame.com/iphone-cocos2d/474.html

In the previous section, we talked about particle-related issues. Of course, we will not show any weakness. Today we will continue to give you a brief introduction and explanation of the physical system;

First, we will introduce how to add the box2d development lib package to cocos2d, because when you use the cocos2d engine to develop a game, you will choose the cocos2d framework when creating projects, instead of directly using the cocos2d framework of the physical system, it suddenly needs to use the physical system in the project in the future (this often happens, as to why, kids shoes know ~), OK. First, create a common cocos2d project;

OK. Follow these steps to add box2d> Lib:

1. copy the Lib package of box2d to the project you just created, and then right-click the libs folder of the project to import it to the project. (If you do not have the Lib package of box2d, create a cocos2d-box2d project)

2. double-click your project name to open the configuration information window by default, click the build settings tab, and then find the "Search paths" column on the page, add "XX/Libs" to "User header search paths". Here, XX is your project name; next, set the "always serch paths" option to yes on the top of the "user header search paths" item, and the default value is no. You must set it here;

3. Finally, commadn + B (My xcode for Lion) compiles the project code. If the code is successfully compiled, OK. You can use it;

Next I will give you a brief introduction to how to use the box2d physical system in cocos2d. Although there are few materials and tutorials on box2d, I will not give a detailed introduction and explanation here, as box2d has been explained in detail and two physical games in my upcoming android game development book, here we will introduce some important methods;

For ease of understanding, here I directly use xcode to directly create a cocos2d-Box2d project, and then simple modifications:

//// Helloworldlayer. MM // box2dproject /// created by hua ming Li on 11-9-14. // himi /// import the interfaces # import "helloworldlayer. H "# define ptm_ratio 32 // enums that will be used as tagsenum {ktagtilemap = 1, ktaganimation1 = 1,}; // helloworldlayer implementation @ implementation helloworldlayer + (ccscene *) scene {ccscene * scene = [ccscene node]; helloworldlayer * layer = [helloworldlayer node]; [scene Addchild: layer]; return scene;} // on "init" you need to initialize your instance-(ID) Init {// the physical world is created on the screen, in addition, a rigid body is created around the screen to prevent the rigid body from being in the physical world. // finally, a tick method is called to allow the physical world to constantly simulate if (Self = [Super init ]) {self. istouchenabled = yes; self. isaccelerometerenabled = yes; cgsize screensize = [ccdirector shareddire]. winsize; cclog (@ "screen width % 0.2f screen height % 0.2f", screensize. width, screensize. height );/ /Define the Gravity Vector. b2vec2 gravity; gravity. set (0.0f,-10.0f); bool dosleep = true; World = new b2world (gravity, dosleep); World-> setcontinuousphysics (true ); // debug draw functionsm_debugdraw = new glesdebugdraw (ptm_ratio); World-> setdebugdraw (m_debugdraw); uint32 flags = 0; flags + = b2debugdraw: e_shapebit; m_debugdraw-> setflags (flags); b2bodydef groundbodydef; groundbodydef. position. set (0, 0); // bottom-left corner b2body * groundbody = World-> createbody (& groundbodydef); b2polygonshape groundbox; // bottomgroundbox. setasedge (b2vec2 (0, 0), b2vec2 (screensize. width/ptm_ratio, 0); groundbody-> createfixture (& groundbox, 0); // topgroundbox. setasedge (b2vec2 (0, screensize. height/ptm_ratio), b2vec2 (screensize. width/ptm_ratio, screensize. height/ptm_ratio); groundbody-> createfixture (& groundbox, 0 );// Leftgroundbox. setasedge (b2vec2 (0, screensize. height/ptm_ratio), b2vec2 (0, 0); groundbody-> createfixture (& groundbox, 0); // rightgroundbox. setasedge (b2vec2 (screensize. width/ptm_ratio, screensize. height/ptm_ratio), b2vec2 (screensize. width/ptm_ratio, 0); groundbody-> createfixture (& groundbox, 0); cclabelttf * label = [cclabelttf labelwithstring: @ "himi" fontname: @ "marker felt" fontsize: 32]; [self addchild: Labe L z: 0]; label. position = CCP (screensize. width/2, screensize. height-50); [self schedule: @ selector (tick :)];} return self;} // box2d debugging mode, because the physical world cannot be reached, in this case, the rigid bodies in the physical world cannot be seen. // However, to facilitate development and debugging, box2d provides the debugging class, the main function is to show all rigid bodies and joints in the physical world by using line frames. // This makes it easy to set the positional relationship between your body and sprite ----- (void) draw {gldisable (gl_texture_2d); gldisableclientstate (gl_color_array); gldisableclientstate (gl_texture_coord_array); World-> drawdebugdata ();/ /Restore Default GL statesglable (gl_texture_2d); glableclientstate (gl_color_array); glableclientstate (gl_texture_coord_array);} // --- add a rigid body. First, create the skin of the rigid body, you can understand that this skin is a rigid body property, and then wrap a rigid body using the skin-(void) addnewspritewithcoords :( cgpoint) p sp :( ccsprite *) sprite {cclog (@ "add sprite % 0.2f X % 02.f", P. x, p. y); Sprite. position = CCP (P. x, p. y); b2bodydef bodydef; bodydef. type = b2_dynamicbody; bodydef. position. set (P. x/PTM _ Ratio, P. y/ptm_ratio); // assign the genie information to the rigid body skin, so that the motion track of the genie can synchronize with the Motion Track of the newly created Rigid Body in the physical world bodydef. userdata = sprite; b2body * Body = World-> createbody (& bodydef); b2polygonshape dynamicbox; dynamicbox. setasbox (. 9f ,. 9f); b2fixturedef fixturedef; fixturedef. shape = & dynamicbox; fixturedef. density = 1.0f; fixturedef. friction = 0.3f; body-> createfixture (& fixturedef); // apply a force to the body b2vec2 force = body-> getworldvector (b2vec2 (1 000.0f, 6000000f); b2vec2 point = body-> getworldpoint (b2vec2 (0.4f, 0.4f); Body-> applyforce (force, point ); // ---------- Note 1 himi} // In this method, physical simulation is performed on the physical world first, and then the rigid body motion track in the physical world is continuously traversed and copied to the corresponding genie-(void) TICK: (cctime) dt {int32 velocityiterations = 8; int32 positioniterations = 1; World-> step (DT, velocityiterations, positioniterations ); for (b2body * B = World-> getbodylist (); B; B = B-> getnext () {If (B-> getuserdata ()! = NULL) {// synchronize the atlassprites position and rotation with the corresponding bodyccsprite * myactor = (ccsprite *) B-> getuserdata (); myactor. position = cgpointmake (B-> getposition (). x * ptm_ratio, B-> getposition (). y * ptm_ratio); myactor. rotation =-1 * cc_radians_to_degrees (B-> getangle () ;}}// --- the touch screen will add a body and a genie in the position of the coordinates of the player's touch screen-(void) cctouchesended :( nsset *) touches withevent :( uievent *) event {for (uitouch * touch in touches) {cgpoint location = [Touch locationinview: [Touch view]; location = [[ccdirector shareddire] converttogl: location]; ccsprite * sprite = [ccsprite spritewithfile: @ "icon.png"]; [self addchild: SPRITE]; [self resume: Location SP: sprite] ;}}-(void) accelerometer :( uiaccelerometer *) accelerometer didaccelerate :( uiacceleration *) Acceleration {static float prevx = 0, prevy = 0; // # define kfilterfactor 0.05f # define kfilterfactor 1.0f // don't use filter. the code is here just as an examplefloat accelx = (float) acceleration. x * kfilterfactor + (1-kfilterfactor) * prevx; float accely = (float) acceleration. y * kfilterfactor + (1-kfilterfactor) * prevy; prevx = accelx; prevy = accely; b2vec2 gravity (-accely * 10, accelx * 10 ); world-> setgravity (gravity);}-(void) dealloc {Delete world; World = NULL; Delete m_debugdraw; [Super dealloc];} @ end

Here I will only describe the important methods. The main changes are as follows:Note 1Here, I place a force on the rigid body created every time the player touches the screen to let the rigid body move, the trajectory of this movement will also change according to the gravity direction of the physical world you set. In the current project, the gravity direction is vertical, and there is no change in the X axis;

Note that, since box2d is a C ++ code, if you use box2d, first put your delegate. change M class to delegate. mm, and the Implementation class (. m) the format class should be changed (. mm) format, so that the compiler will know that it is a mixed code. Otherwise, an error will be reported when it is compiled as object-C;

Run the following command:

It can be seen that a line segment is surrounded by an icon. This is the debugging drawing provided by box2d, and the invisible rigid body is drawn;

Here I have to talk about some children's shoes. For example, I have previously written an example of a simple physical system ball on Android. I wrote in my blog that I want to create a ball through a touch screen, however, many children's shoes asked me if the project was not effective, and I collapsed... You asked me

Source code wanted to upload, but found a click to upload resources on the tragedy can not open the page, you can directly create a cocos2d-box2d project, and then the helloworldlayer. mm in the Code into my above code can ~

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.