Last active
April 24, 2024 03:08
-
-
Save ShimShamSam/f10d60ad39040ed6add0 to your computer and use it in GitHub Desktop.
Phaser Physics - Stop sideways velocity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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