Two vectors are returning different angles

Godot Version

4.2.1

Question

I’m trying to add drift the player character. As a first I want to figure out which way the character is turning. :

	# Calculate drift  --------------------------------------
	var angle_diff = snapped(velocity.angle(), 0.01) - snapped(direction.angle(), 0.01)
	if angle_diff < 0: #right
		pass
		print("right")
	else:
		pass
		print("left")

	print("direction_angle: ",direction.angle())
	print("velocity angle : ", velocity.angle())
	print("angle diff: ", angle_diff)

Although when the player is turning left and has the direction (-1,0) the angle diff returns -6
but when turning right and has the direction (-1,0) the angle diff returns 0. And i cant figure out how to fix it

Full script:

extends CharacterBody2D

const SPEED = 300.0
const TURN_SPEED = 8.0

# Driving vars
var max_speed = 800
var speed = 200
var acceleration = 50
var deceleration = 0.1

var direction 
var latest_direction = Vector2(0,0)


func _physics_process(delta):
	direction = Input.get_vector("ui_left","ui_right","ui_up","ui_down")
	
	if direction:
		# Get the angle to the desired direction
		var target_angle = direction.angle()
		# Smoothly rotate towards that angle
		rotation = lerp_angle(rotation, target_angle, TURN_SPEED * delta)

	if direction:
		var target_velocity: Vector2 = transform.x * max_speed
		velocity = velocity.move_toward(target_velocity, acceleration)

	# Calculate drift  --------------------------------------
	var angle_diff = snapped(velocity.angle(), 0.01) - snapped(direction.angle(), 0.01)
	if angle_diff < 0: #right
		pass
		print("right")
	else:
		pass
		print("left")

	print("direction_angle: ",direction.angle())
	print("velocity angle : ", velocity.angle())
	print("angle diff: ", angle_diff)
	# --------------------------------------------------------------------------
	# Apply standard deceleration
	velocity = velocity.move_toward(Vector2.ZERO, deceleration)
	# --------------------------------------------------------------------------
	
	if direction != Vector2(0,0):
		latest_direction = direction
	move_and_slide()

Any and all help is appreciated :slight_smile:

I’d suggest using angle_difference() rather than subtracting.

2 Likes

… That was an easy fix
Thank you!

1 Like