I need help i have been working for 3 days on this one bug

Godot Version

Godot_v4.2.2-stable

Question

i have been working for three days to try and make this animated sprite flip towards the direction of the mouse but it doesn’t i am very new to gdscipt and am highly confused by most things please send help. here is my character movement script

extends CharacterBody2D


const SPEED = 300.0
const JUMP_VELOCITY = -400.0

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")


@warning_ignore("unused_parameter")
func _physics_process(delta):
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var xdirection = Input.get_axis("ui_left", "ui_right")
	if xdirection:
		velocity.x = xdirection * SPEED
		#AnimatedSprite2D.animation = "run"
	else:
		velocity.x = move_toward(velocity.x, 0, 15)

	var ydirection = Input.get_axis("ui_up", "ui_down")
	if ydirection:
		velocity.y = ydirection * SPEED
		#AnimatedSprite2D.animation = "run"
	else:
		velocity.y = move_toward(velocity.y, 0, 15)

	move_and_slide()
	
	var flipbool = int (get_global_mouse_position().x < position.x) * 2 
	CharacterBody2D.scale.x = flipbool + 1

Hey

Don’t you want to flip the AnimatedSprite2D instead of the Character?
This class have a field designed for that:

Also, when I read your two last line it looks like it can only be a scale x of 1 or 3:

In case of mouse at the right:

var flipbool = int(false) * 2 == 0
CharacterBody2D.scale.x = 0 + 1

In case of mouse at the left:

var flipbool = int(true) * 2 == 2
CharacterBody2D.scale.x = 2 + 1

You could:

if get_global_mouse_position().x < position.x == true:
        CharacterBody2D.scale.x = -1
else:
        CharacterBody2D.scale.x = 1        

But once again those affect the CharacterBody2D as I don’t use those I am not sure of the behavior regarding the children (animated sprite and all)
You might want to directly affect your AnimatedSprite2D.flip_h field

Hope that helped, good luck!

1 Like

Thanks

i have started getting this error?
invalid get index ‘scale’ (on base: ‘AnimatedSprite2D’)

Well, indeed scale is not a field of AnimatedSprite2D
what was your goal? Horizontaly flipping the sprite?

That could be achieve by:

# The following line should show the path to your sprite
@onready var animated_sprite = $CharacterBody2D/AnimatedSprite2D

///
///
if get_global_mouse_position().x < position.x == true:
    animated_sprite.flip_h = true
else:
    animated_sprite.flip_h = false
1 Like