Animation of characterbody2d, not playing the correct animation based on the position of the mouse

Godot Version

v4.3.stable

Question

Hello, I am trying to get this character to play the correct animation based on the global_position of the mouse (or anything else) for example. The character should play the look up animation if the mouse is above the character, and should look down when the mouse is below the character etc etc.

This might seem to work as intended at first glance, but I am having a really weird issue with this, where this logic does not stay local to the character object, so if I move this character beyond 0,0 coordinates in the scene tree, then if I move the mouse around the position where I placed the character that is not at 0,0, the animations don’t play correctly, but if I move the mouse around 0,0 the character object displays the corrects animations. I have no idea why this happens

Some help would be appreciated.
Hopefully my explanation made sense to you. I am not sure if it’s even possible to post gifs on this to show you what I mean.

And please be patient with me, and polite when you are trying to help.

This is what the code of the character object looks like.


@onready var animated_sprite_2d = $AnimatedSprite2D
var direction = Vector2.ZERO
var mouse_location


func _physics_process(delta):
	mouse_location = get_global_mouse_position()
	print_debug("Mouse Location ", mouse_location)
	play_anim()


func play_anim() -> void:
	var direction_vec = Vector2.ZERO
	if abs(mouse_location.x) > abs(mouse_location.y):
		direction_vec = "right" if mouse_location.x > 0 else "left"
	else:
		direction_vec = "down" if mouse_location.y > 0 else "up"
	
	animated_sprite_2d.play("look_" + direction_vec)```

mouse_location isn’t being compared to your character’s position, it is being compared to the (absolute) origin. You should probably be doing something like:

if abs(mouse_location.x - position.x) > abs(mouse_location.y - position.y):
    direction_vec = "right" if mouse_location.x > position.x else "left"
    etc
1 Like