Implementing basic movement, struggling with automatic slowing down

Godot Version

Godot 4.3

Question

I’m trying to add a sort of “ice physics” (for lack of a better term) to try and slow down the player before stopping. However, the body instantly stops no matter what.

I’ve also noticed that if I remove the direction.x and direction.z in the else section, the player does slow down, but it suddenly shoves the player in what I’m guessing are the global x and z directions. If this assumption is true, how would I make it look for the local x and z directions of the player’s body?


	#declaring movement variables:
var initialVelocity : float = 1
var initialV : float = 1
var maxVelocity : int
var velocityIncreaseRate : float

func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity += get_gravity() * delta
	
	var input_dir := Input.get_vector("move left", "move right", "move forward", "move back")
	var direction = (body.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	
	if direction:
		maxVelocity = 6
		velocityIncreaseRate = 0.05
		#temp vars, as these will be influenced by equipment
		
		if initialVelocity < maxVelocity:
			initialVelocity += velocityIncreaseRate
		velocity.x = direction.x * initialVelocity
		velocity.z = direction.z * initialVelocity
		
	else:
		if initialVelocity > initialV:
			initialVelocity -= velocityIncreaseRate*3
		velocity.x = direction.x * initialVelocity
		velocity.z = direction.z * initialVelocity
			
	print(initialVelocity)
    #print exists for testing purposes
	move_and_slide()

While there is no input direction will be a zero vector, which means you are setting velocity.x and z to 0, no matter what value initialVelocity has. Also, you shouldn’t change velocity.x and z independently, change them as a Vector via move_toward().

	var target_velocity : Vector3 = direction * maxVelocity
	target_velocity.y = velocity.y
	
	if direction:
		velocity = velocity.move_toward(target_velocity, acceleration * delta)
	else:
		velocity = velocity.move_toward(target_velocity, deacceleration * delta)
3 Likes