Hey there! I'm writing my first movement controller and I've hit a small roadblock.
I'm trying to stop the player from accelerating when they've hit their max speed, but still allow them to decelerate by moving in the opposite direction.
I got something working that exhibited this behavior, but it was a mess of if statements, and I'm wondering if anyone has found a solution to get the job done cleanly and efficiently.
A sample of my code for your reference:
func update_velocity_xz(delta):
var velocity2D = Vector2(velocity.x, velocity.z)
var temp = Vector2()
Apply friction on ground (FRICTION)
if is_on_floor():
velocity.x = velocity2D.move_toward(Vector2.ZERO, FRICTION delta).x
velocity.z = velocity2D.move_toward(Vector2.ZERO, FRICTION delta).y
Apply friction in air (AIR_RESISTANCE)
else:
velocity.x = velocity2D.move_toward(Vector2.ZERO, AIR_RESISTANCE delta).x
velocity.z = velocity2D.move_toward(Vector2.ZERO, AIR_RESISTANCE delta).y
Apply raw movement acceleration to temp (MAX_SPEED, ACCELERATION)
temp.x = (ACCELERATION delta) inputVector.x
temp.y = (ACCELERATION delta) inputVector.y
Rotate direction of acceleration relative to direction of KinematicBody
temp = return_rotated_local(temp)
Apply temp to velocity x and y
velocity.x = velocity.x - temp.x
velocity.z = velocity.z - temp.y