Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Box2d object follow a predetermined path

I'm making a game in which a certain object (modelled as a box2d body) has to follow a fixed path. Is there a way by which I can specify the path coordinates and make the object advance over it for each dt?

Thanks

like image 481
Nav Avatar asked Feb 22 '23 00:02

Nav


2 Answers

Another option:

  • Attach a mouse joint to your body
  • Use setTarget method of the mouse joint to move the body
like image 157
hiepnd Avatar answered Feb 24 '23 16:02

hiepnd


You should use a Kinematic body, but you can't change its position manually, you have to change its speed for the dynamics and collisions to be applied correctly.

I suggest the following algorithm:

1st - Calculate the position on the track that the body should be in on the next dt.

2nd - Make a vector going from the position where the body is to the next position.

3rd - Normalize it.

4rd - Calculate how much speed you need so that the body will be in that position on the next loop, and multiply that speed on the vector.

5th - Apply this vector to the Linear Velocity of the body.

Note: make sure the kinematic body has zero drag so that calculating the 4th step is easier.

I never did something like this, I think it can be done this way. Hope it helps :)

like image 26
Rui Campos Avatar answered Feb 24 '23 15:02

Rui Campos