I'm trying to add strafe-leaning to my FPS game, and I want it to be based on the player's velocity (like Quake) but I can't figure out how to get the player velocity x-component on a scale of -1 (strafing left) to 1 (strafing right). I've tried pulling directly from the input axis/vector, but since I'm using digital inputs, the leaning snaps between on and off. I've also tried remapping the x-velocity to a value from -1 to 1 and that spun the camera around so much it was incomprehensible what it was doing. Has anyone solved this particular issue, or could suggest a different method to try?
#How to Get a Velocity Component on a Scale of -1 to 1?
12 messages · Page 1 of 1 (latest)
If you have a max velocity you can just do velocity.x / max_x_velocity
That's a good thought, but when I tested it, it only worked when leaning one way, or when facing a certain direction.
Possibly the wrong answer, but if you're testing right now it's something to try - I assume you've got a velocity Vector3 and and facing Vector3. Have you tried velocity.dot(facing.rotated(Vector3.ZERO, PI/2)) ?
That's "work out what's 90 degrees from your current facing" and then "work out what the velocity in that axis is".
Wait, Vector3.AXIS_Y instead of ZERO.
velocity.dot(facing.rotated(Vector3.AXIS_Y, PI/2)) / max_x_velocity
I couldn't seem to get that to work. It kept giving me an error about using the wrong variable type.
Turns out that Vector3.AXIS_Y is not a valid variable there. It wants a Vector3, not an int.
Sorry, I'm posting without testing because I assume you have the complete setup ready to drop code into. Does [0, 1, 0] work instead of AXIS_Y?
Tested, this will give you a value for whether the velocity is left or right compared to the direction that you're facing:
# Assume these two come from elsewhere
var facing = Vector3(1, 0, 1).normalized()
var velocity = Vector3(x, 0, z)
var max_x_velocity = 2
var axis_y = Vector3(0, 1, 0)
var dotprod = velocity.dot(facing.rotated(axis_y, PI/2)) / max_x_velocity
print("Dotprod: ", dotprod)
I should have said Vector3.UP instead of Vector3.AXIS_Y.