Skip to content

Instantly share code, notes, and snippets.

@ShimShamSam
Last active April 24, 2024 03:08
Show Gist options
  • Save ShimShamSam/f10d60ad39040ed6add0 to your computer and use it in GitHub Desktop.
Save ShimShamSam/f10d60ad39040ed6add0 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment