Skip to content

Instantly share code, notes, and snippets.

@photonstorm
Forked from ShimShamSam/stopSidewaysVelocity.js
Created February 24, 2016 11:39
Show Gist options
  • 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

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