Jump to content

P2 Physics Limit the Speed of a Sprite


Taleforge
 Share

Recommended Posts

Hi,

 

I want to limit the Speed of a sprite (P2JS enabled), wich is accelerated by

sprite.body.thrust(400);

and slowed by

sprite.body.reverse(400)

Its simply like the new P2 - Thrust-Example. where you control a spaceship. How can I limit the speed of that sprite?

If the player keeps accelerating the speed will go insane!

Link to comment
Share on other sites

  • 1 month later...

I hit the same wall trying to migrate from ARCADE to P2 physics.

 

I made a working solution for speed capping for want of better solution. I put into a separate function so that all my P2JS-bodies can check their speeds with it:

var limitSpeedP2JS = function(p2Body, maxSpeed) {    var x = p2Body.velocity.x;    var y = p2Body.velocity.y;    if (Math.pow(x, 2) + Math.pow(y, 2) > Math.pow(maxSpeed, 2)) {        var a = Math.atan2(y, x);        x = -20 * Math.cos(a) * maxSpeed;        y = -20 * Math.sin(a) * maxSpeed;        p2Body.velocity.x = x;        p2Body.velocity.y = y;    }    return p2Body;}

I have absoluteley no clue what the -20 magic number is about, but it was needed for my game to limit the speeds correctly. It might be related to masses, gravity, drag, damping, or something else entirely.

 

Hope that works for you as well.

Link to comment
Share on other sites

  • 5 months later...

I use a limiting function inside the update loop. The correct way would be to place the limiting function somewhere inside p2's substep loop which is called multiple times (10 by default) during a single render update. The constraining happens far too late in the update loop and that's why you might run into tunneling or some kind of jittering especially during lower frame rates. It should be fine in most cases so it's worth a try.

 

Here a small example based on the mentioned thrust example:

http://jsfiddle.net/sh036s95/

 

Regards

George

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...