0 votes

How to check which side of the player the cursor is on (left or right)?

In my case, I need to flip the player's sprite when the cursor is on the left/right side (size=1 - right, size=1 - left). I used for this rotation degrees of my weapon, which is facing towards the cursor:

func _process(delta):

    if rotation_degrees >= -90 and rotation_degrees <= 90:
        find_parent("player").scale.x = 1
        find_parent("player").scale.x = -1

    if rotation_degrees <= -270:
        print("set 90")
        rotation_degrees = 90
    if rotation_degrees >= 270:
        print("set -90")
        rotation_degrees = -90

But I did not succeed: weapon and player flipped incorrectly if you shake the cursor very quickly.

Godot version 3.2.3.stable
in Engine by (137 points)

1 Answer

+1 vote
Best answer

You can get the location of the cursor at any time with getglobalmouse_position().

You can then compare that with the player's global position.

If the mouse's position is greater that the player's, it is on the right of the player and vice versa.

So you can do this in the player script:

if get_global_mouse_position().x > global_position.x:
    scale.x = 1
elif get_global_mouse_position.x < global_position.x:
    scale.x = -1

Additionally instead of changing the scale of the player you can just flip the sprite using $Sprite.flip_h = true/false if you want to. I hope this helped!

by (570 points)
selected ago by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.