How to flip a sprite left/right with the mouse direction

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By i9btTheNoob

I can’t flip my sprite using the mouse direction, but i cant think of a way to impliment it. I don’t know how to get the mouse position out as a variable for example “var mouse_postition = …”. What should it be equal to? Should i turn it into an int?

My idea is somethink like:

var mouse_position = "idk what should be here"
if mouse_position > 0:
   flip_h = false
elif mouse_position < 0:
   flip_h = true

Is somethink like that possible? If anyone has some advice how should i do it or any kinds of tips it would be really appriciated!!!

Language: GDScript
Version: Godot 3.5

You can use P0werman1’s answer below to get the current X coordinate of the mouse. You’ll probably want to compare that value with the current X coordinate of your sprite. If mouseX > spriteX, the sprite would face right. If mouseX < spriteX, the sprite would face left.

jgodfrey | 2023-05-15 17:41

Yes, I hadn’t thought of that.

P0werman1 | 2023-05-15 18:12

:bust_in_silhouette: Reply From: P0werman1

get_viewport().get_mouse_position().x
however, remember that (0,0) is the top left corner

:bust_in_silhouette: Reply From: CassanovaWong

Lot of ways to do this.
here’s one:

match sign(global_position.direction_to(get_global_mouse_position().x):
    1:
       flip_h = false
    -1:
       flip_h = true
:bust_in_silhouette: Reply From: CharlesGrimes

To flip a sprite left or right based on the mouse direction in Godot’s GDScript, you can use the get_global_mouse_position() function to obtain the mouse position. Here’s an example of how you can implement it:

extends Sprite

func _process(delta):
    var mouse_position = get_global_mouse_position()

if mouse_position.x > position.x:
    flip_h = false
elif mouse_position.x < position.x:
    flip_h = true

In this example, get_global_mouse_position() retrieves the mouse position as a Vector2. We then compare the x-coordinate of the mouse position with the x-coordinate of the sprite’s position. If the mouse is to the right of the sprite, we set flip_h to false (no flipping). If the mouse is to the left of the sprite, we set flip_h to true (flipping horizontally).

Remember to attach this script to your sprite node in Godot. Also, ensure that you have set up the appropriate input handling in Godot, such as enabling the mouse and registering mouse-related signals, to receive accurate mouse positions.

I hope this helps!