Skip to content

Instantly share code, notes, and snippets.

@photonstorm
Forked from ShimShamSam/stopSidewaysVelocity.js
Created February 24, 2016 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save photonstorm/d67acb39490d93da3460 to your computer and use it in GitHub Desktop.
Save photonstorm/d67acb39490d93da3460 to your computer and use it in GitHub Desktop.
Phaser Physics - Stop sideways velocity
/**
* Negate sideways velocity on an object being acted upon by a Phaser physics engine.
* The primary use for this is to simulate vehicle movement by negating "drift" when the vehicle turns.
* @param {Phaser.Sprite} sprite The sprite whose sideways velocity you want to negate
*/
function stopSidewaysVelocity(sprite) {
// Recycle the same object to conserve memory
if(!stopSidewaysVelocity.sideways) {
stopSidewaysVelocity.sideways = {};
}
var body = sprite.body;
var velocity = body.velocity;
var rotation = body.rotation + Math.PI / 2;
var sideways = stopSidewaysVelocity.sideways;
sideways.x = Math.cos(rotation);
sideways.y = Math.sin(rotation);
var dot_product = velocity.x * sideways.x + velocity.y * sideways.y;
velocity.x = sideways.x * dot_product;
velocity.y = sideways.y * dot_product;
}
@ShimShamSam
Copy link

I will most likely be revising my original gist in the future to accept a second argument that dictates the friction coefficient, rather than doing a full negation on orthogonal velocities.

Furthermore, orthogonal to the angle of the sprite (Math.PI / 2) works in my use case, but I can imagine situations where people might need different friction coefficients based on different angles of movement. For example, they might want angles between 45 and 135 degrees to have twice as much friction as angles between -45 and 45 degrees.

Would it be worthwhile for me to try my hand at something like that so it can be folded into Phaser (or Lazer)?

@ForgeableSum
Copy link

there's no explanation as to how this works. When do you run your function, before or after the new velocity is applied? I tried both and neither worked.

@ShimShamSam
Copy link

Run it every frame in your sprite's update function, preferably after any logic to apply new velocity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment