0
\$\begingroup\$

I have a set of 2D coordinates. Their positions are regular on the X axis, but unpredictable on the Y axis:

Coordinates set

I would like to create slim platform between each point in order tu use it as ground for my game, expecting a result like this:

enter image description here

I'm working with Box2D, so I thought about create boxes like this:

float x1, y1, x2, y2; // Coordinates between two points
float centerX, centerY;
float differenceX, differenceY;
float width;
b2BodyDef bodyDef;
b2Body* body;
b2PolygonShape shape;

centerX = (x1 + x2) / 2.0;
centerY = (y1 + y2) / 2.0;
differenceX = x2 - x1;
differenceY = y2 - y1;
width = sqrtf(differenceX * differenceX + differenceY * differenceY);
height = 10.0f

bodyDef.position.Set(centerX, centerY);
bodyDef.angle = -M_PI / 4.0f * width / height
body = world.CreateBody(&bodyDef);
shape.SetAsBox(width, 10.0f);
body->CreateFixture(&box, 0.0f);

But the wrong part of this code seems to be on angle. I cannot find the correct rotation between two points from their coordinates.

Is there a correct math formula to find it?
Or am I simply wrong to use rectangular boxes to trace it, and should I use something else? Like a b2PolygonShape?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Do not use boxes for this kind of terrain. There are numerous problems that arise with using boxes, namely "catching" of objects on the intersections between the boxes.

Box2D provides Edge Shape (line) primitives as well as a Chain Shape that far better suites your purpose.

From the linked manual:

// This a chain shape with isolated vertices
b2Vec2 vs[4];
vs[0].Set(1.7f, 0.0f);
vs[1].Set(1.0f, 0.25f);
vs[2].Set(0.0f, 0.0f);
vs[3].Set(-1.7f, 0.4f);
b2ChainShape chain;
chain.CreateChain(vs, 4);

For your terrain, you'd just generate the array of points and then create the Chain Shape.

Pay attention as well to the ghost vertices feature which is necessary to correctly use multiple distinct Chain Shapes that adjoin each other without generating similar collision problems to the box solution.

\$\endgroup\$
0
\$\begingroup\$

You can compute the angle with the arctangent function atan2 (from math.h)

float angle = atan2(differenceY, differenceX);

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .