Introduction to Cocos2d-x physical engine: hellophysicsworld

Source: Internet
Author: User
Tags addchild
Let's take an example to introduce the development process of using physical engines in Cocos2d-x 3. X and get familiar with the use of these Apis. In the running scenario of this instance, after the scenario is started, the player can touch and click the screen. Each time the screen is touched, a new genie will be generated at the touch point, the running of the genie is a free-body movement.



Hellophysicsworld instance

Shows the general steps for using the physical engine.



This process is similar to the process in which God creates the world. God first creates the world, and then assigns boundaries to the world. Otherwise, everything will fall into chaos outside the world, finally, God created everything.
Of course, this is only the most basic step. Sometimes it also needs Collision Detection and joint processing. Next we will follow this step to introduce the code section. First, let's take a look at the helloworldscene. h file. Its code is as follows:
#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"USING_NS_CC;class HelloWorld : public cocos2d::Layer{public:    static cocos2d::Scene* createScene();     virtual bool init();  virtual bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);①    CREATE_FUNC(HelloWorld);void addNewSpriteAtPosition(Vec2 p);②};#endif // __HELLOWORLD_SCENE_H__


The Code in line ① declares the ontouchbegan function, which is used to respond to a single touch event. The Code in line ② defines the creation of the sprite function, which creates a Sprite object in the position of a touch click.
Create a physical world in helloworldscene. cpp. The Code is as follows:
Scene* HelloWorld::createScene(){    auto scene = Scene::createWithPhysics();①scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);②        auto layer = HelloWorld::create();    scene->addChild(layer);    return scene;}


The above line code scene: The createwithphysics () statement is the creation scenario. This is a world scenario with a physical engine. The createwithphysics () function will initialize the physical engine in the scenario, we can use the getphysicsworld () function of the scenario to obtain the initialized physical world (physicsworld) object. We can also set the physical world here as needed, where the second line of code is set to draw a debugging mask in the physical world, which will draw the shape of the object. Because if an object in the world is not bound with the genie, we cannot see it. This is mainly used for debugging. When the debugging is completed and the game is released, we need to disable it. Shows the scenario for disabling the rendering of a debug mask.



The code for specifying the world boundary in helloworldscene. cpp is as follows:
Bool helloworld: Init () {If (! Layer: Init () {return false;} size visiblesize = Director: getinstance ()-> getvisiblesize (); vec2 origin = Director: getinstance () -> getvisibleorigin (); // defines the world's boundary Auto Body = physicsbody: createedgebox (visiblesize, physicsbody_material_default, 5.0f); ① auto edgenode = node: Create (); ② edgenode-> setposition (vec2 (visiblesize. width/2, visiblesize. height/2); ③ edgenode-> setphysicsbody (body); ④ this-> addchild (edgenode); ⑤ settouchenabled (true ); ⑥ // set it to single-touch settouchmode (touch: dispatchmode: one_by_one); 7return true ;}


The above code helloworld: init is the initialization layer function. In this function, we can specify the world boundary. The world boundary is also an object. Line ① physicsbody of the Code :: createedgebox is an object creation object. The static function createedgebox specifies that the world boundary is a rectangular box. The first parameter of the createedgebox function specifies the size of the rectangle. The second parameter is to set the material. The constant physicsbody_material_default is the default material. The material is defined by the physicsmaterial structure. The physicsmaterial structure includes density (density) and friction (friction coefficient) and restitution (elastic coefficient ). Density can be used to calculate the mass of an object. The density can be zero or positive. The friction coefficient is usually set to 0.0 ~ Between 1.0 and 0.0 indicates that there is no friction, and 1.0 will produce strong friction. The value of the elastic coefficient is usually set to 0.0 ~ Between 1.0, 0.0 indicates that the object will not bounce, and 1.0 indicates that the object will rebound completely, that is, elastic collision. The third parameter of the createedgebox function is to set the edge width.
Line ② of the code is to create a Boundary Node object, which serves as a world boundary object. Line ③ of code is to set the location of the Node object. Line 4 Code edgenode-> setphysicsbody (body) is used to set object objects related to nodes. Use this statement to associate node objects (such as Genie) in game scenarios with objects. The fifth line of code is to add the Node object to the layer.
Line 6 of the Code, settouchenabled (true), is to enable Layer-start touch event support. The line 7 Code settouchmode (touch: dispatchmode: one_by_one) is used to set the touch mode to single-point touch.
Other codes of helloworldscene. cpp are as follows:
bool HelloWorld::onTouchBegan(Touch* touch, Event* event)①{Vec2 location = touch->getLocation();addNewSpriteAtPosition(location);return false;}void HelloWorld::addNewSpriteAtPosition(Vec2 p) ②{        auto sp = Sprite::create("Ball.png");③sp->setTag(1);④auto body = PhysicsBody::createCircle(sp->getContentSize().width / 2);⑤//auto body = PhysicsBody::createBox(sp->getContentSize());⑥    sp->setPhysicsBody(body);⑦    sp->setPosition(p);this->addChild(sp);}


The first line of the above Code is the function called during single-point touch. In this function, the addnewspriteatposition (location) function is called to create a Sprite object at the touch point.
The Code in line ② defines the addnewspriteatposition function. The Code sprite: Create ("ball.png") in line ③ creates a Sprite object, and the code in line ④ SP-> settag (1) is to set the tag attribute of the Genie. During the collision check, the tag attribute can be used to determine and obtain the genie object.
The fifth line of code is to create a circle-shaped object through the static createcircle function of physicsbody. Physicsbody also has many similar create functions, such as createbox, createcircle, createpolygon, and createedgepolygon. These functions correspond to physical shapes. The createcircle function is described in detail here. The createcircle function API is as follows:
Static physicsbody * createcircle (float radius,
Const physicsmaterial & material = physicsbody_material_default,
Const vec2 & offset = vec2: Zero
)
Here, the first parameter radius is to set the circle radius, and the second parameter material is the material, which can be omitted. The default value is physicsbody_material_default, so in helloworld: Init () when defining the world boundary in the function, the material parameter in physicsbody: createedgebox can also be omitted. The third parameter offset is the offset, which can be omitted. The default value is vec2: zero.

Line 6 code physicsbody: createbox (SP-> getcontentsize () is used to create a rectangular box without edges. Line 7 Code SP-> setphysicsbody (body) is used to set object objects related to the genie.



More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to Cocos2d-x Technology Discussion Group: 257760386

Welcome to Zhijie IOS public classroom Platform


Introduction to Cocos2d-x physical engine: hellophysicsworld

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.