I am trying to move a dynamic body from point A to point B using Phaser 2.4.6 and the p2.js version included with it. It is really important that the body accurately stops at the destination point and not behind the point or after it passed it (very low tolerances are acceptable). I have tried two approaches so far, and failed with both:
- Use a Phaser tween to change the coordinates of the body throughout the route that I want it to move on. This works beautifully, except the body can skip over static bodies.
Sample code:
game.add.tween(sprite.body).to(
{ x: destinationX, y: destinationY },
timeInterval,
Phaser.Easing.Quadratic.InOut,
true
);
- Use the p2
forceproperty to move the body on the desired path. The collisions with other bodies work well this time, but it is almost impossible to make the body stop at exactly the coordinates I want it to. I tried to decrease the force applied as the body approaches the destination, which works perfect in 90% of the cases. However, in low-performance scenarios the animation is "jittery" (which is to be expected) but also fails to hit the target point and goes over it, sometimes by a lot. I would even accept the option to forcefully stop the body when it hits the destination and hurt the realism of the scene a little bit, but I was unable to do that (tried to set both force and velocity to 0, damping to 1, etc. - nothing worked).
Below some sample code (in the Phaser engine sprite.body.data is pointing to the p2.js physics body):
// OUTSIDE OF THE GAME LOOP:
var magnitude = game.physics.p2.pxmi(-speed);
var angle = entity.body.data.angle + Math.PI / 2;
var forceX = (magnitude * Math.cos(angle)) / 10;
var forceY = (magnitude * Math.sin(angle)) / 10;
// IN THE GAME LOOP:
sprite.body.data.force[0] = forceX;
sprite.body.data.force[1] = forceY;
// Decrease forceX and forceY as the body approaches the destination
Can anybody please provide some suggestions? I am lost at this point, so I could even use an educated guess from someone familiar with some other physics engine.
Thank you.
