-
-
Save photonstorm/d67acb39490d93da3460 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; | |
} |
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.
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
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)?