Attributes such as the shape, size, material, density, and elasticity of an object are described by the customizer (fixture) and translated into a fixture. After an object is collided, it will respond according to its own customizer. The main attributes of the customizer are as follows:
-Shape
-Elasticity
-Friction
-Density
Collision between objects depends on the shape of the object. box2d can define the arc, rectangle, and polygon.
{// Circular bodyDef. type = b2_dynamicBody; bodyDef. position. set (2.0, 3.0); // body position b2Body * circleBody = mWorld-> CreateBody (& bodyDef); b2CircleShape circleShape; circleShape. m_p.Set (0, 0); // center, relative to its body position circleShape. m_radius = 0.5; // radius circleBody-> CreateFixture (& circleShape, 1) ;}{// triangle bodyDef. type = b2_dynamicBody; bodyDef. position. set (4.0, 3.0); // body position b2Body * triangleBody = mWorld-> CreateBody (& bodyDef); b2PolygonShape triangleShape; b2Vec2 vertices [3]; // vertex array vertices [0]. set (-0.5,-0.5); vertices [1]. set (0.5, 0.5); vertices [2]. set (0, 1); triangleShape. set (vertices, 3); triangleBody-> CreateFixture (& triangleShape, 1) ;}{// rectangular bodyDef. position. set (8.0, 3.0); b2Body * rectangle = mWorld-> CreateBody (& bodyDef); b2PolygonShape rectangleShape; rectangleShape. setAsBox (1, 2); // set the half-height and half-width rectangle of the rectangle-> CreateFixture (& rectangleShape, 1 );}
Actually, the rectangle is also a polygon. Look at the implementation of the SetAsBox function of the rectangle.
void b2PolygonShape::SetAsBox(float32 hx, float32 hy){ m_vertexCount = 4; m_vertices[0].Set(-hx, -hy); m_vertices[1].Set( hx, -hy); m_vertices[2].Set( hx, hy); m_vertices[3].Set(-hx, hy); m_normals[0].Set(0.0f, -1.0f); m_normals[1].Set(1.0f, 0.0f); m_normals[2].Set(0.0f, 1.0f); m_normals[3].Set(-1.0f, 0.0f); m_centroid.SetZero();}
The internal implementation is the same as the triangle implementation. The vertex array is assigned to the member vertex array of the polygon to calculate the side's normal vector.
Note that the coordinates of the center are relative to the body position, and the vertex coordinates of the polygon are also relative to the body position. The polygon vertices rotate counterclockwise in the right coordinate system.
In box2d, the maximum side of a polygon is 8 by default. If you want more vertex polygon, you need to change this value to a macro defined in Box2D/Common/b2Settings. h.
/// The maximum number of vertices on a convex polygon. You cannot increase/// this too much because b2BlockAllocator has a maximum object size.#define b2_maxPolygonVertices 8
I have not mentioned some basic concepts in box2d here, because many people have translated the official manual into Chinese on the Internet. So if you need it, let's take a look. I try to write some sample code and my own problems. :