Jump to content

Is there a way to set maximum speed for an object?


frokenstein
 Share

Recommended Posts

I am making a video game where you have a spaceship that cannot exceed a certain maximum speed, which for the time being I've set to 100. The problem is that this all depends on the x and y velocity components. The coding involved would have to check for angle as well as the current x and y velocities and make sure neither exceeds their componential max velocity (which depends on what the angle currently is). If I were traveling in a purely x or y direction, the component would max out at 100. But if I were traveling at a 45 degree angle they'd both have to max out at about 70. Is there a function that Phaser provides to do this, or will I need to compute it using my own math?

Link to comment
Share on other sites

It appears the property maxVelocity works on a per x,y component level (at the pixel level) so I guess if you were traveling at 45 degrees you'd achieve max velocity. It's not what I want but I guess I can live with it for the time being. If there is a better solution, please let me know.

Link to comment
Share on other sites

  function constrainVelocity(sprite, maxVelocity) {    if (!sprite || !sprite.body) {return;}    var body = sprite.body    var angle, currVelocitySqr, vx, vy;    vx = body.data.velocity[0];    vy = body.data.velocity[1];    currVelocitySqr = vx * vx + vy * vy;    if (currVelocitySqr > maxVelocity * maxVelocity) {        angle = Math.atan2(vy, vx);        vx = Math.cos(angle) * maxVelocity;        vy = Math.sin(angle) * maxVelocity;        body.data.velocity[0] = vx;        body.data.velocity[1] = vy;        console.log('limited speed to: '+maxVelocity);    }};

this works very well for me..  put the function call into your update loop :)

Link to comment
Share on other sites

  • 2 years later...
 Share

  • Recently Browsing   0 members

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