4

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

Nav
  • 1,185
  • 16
  • 23

2 Answers2

7

Another option:

  • Attach a mouse joint to your body
  • Use setTarget method of the mouse joint to move the body
hiepnd
  • 821
  • 4
  • 14
1

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 :)

Rui Campos
  • 453
  • 2
  • 11
  • check hiepnd's answer, its much easier, and should provide the same result :) – Rui Campos Dec 26 '11 at 13:11
  • Thanks. I did something similar. I used setTransform on the body for step 4 since I knew the next position. Only problem with these methods: transient states must be calculated and specified in onUpdate. Now over to the other method to see if box2d takes over position calculation. – Nav Dec 27 '11 at 08:44