Jump to content

P2 Physics Limit the Speed of a Sprite


Recommended Posts



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


and slowed by


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:





Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

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