frokenstein Posted November 12, 2014 Share Posted November 12, 2014 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? Stathis 1 Link to comment Share on other sites More sharing options...
frokenstein Posted November 12, 2014 Author Share Posted November 12, 2014 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 More sharing options...
valueerror Posted November 12, 2014 Share Posted November 12, 2014 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 Stathis and Sam 2 Link to comment Share on other sites More sharing options...
frokenstein Posted November 13, 2014 Author Share Posted November 13, 2014 Perfect! Thank you. Link to comment Share on other sites More sharing options...
Stathis Posted January 28, 2017 Share Posted January 28, 2017 @frokenstein I had the same exact issue, that I have mentioned here. At first I went for the above solution (thanks @valueerror), but then I realised I can do something like this: sprite.body.velocity.setMagnitude(Math.min(MAX_SPEED, sprite.body.velocity.getMagnitude())); and I think it works fine for me . samme 1 Link to comment Share on other sites More sharing options...
Recommended Posts