frokenstein

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

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?

Share this post


Link to post
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.

Share this post


Link to post
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 :)

Share this post


Link to post
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.

Guest
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.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.