How to flip Sprite Node relative to global mouse position?

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

This script is attached to a KinematicBody2D node. Trying to flip the Body sprite node relative to the mouse cursor’s position. Sprite should flip horizontally (face left) if the x position of the mouse is less than the x position of the player, but different errors say I’ve got it wrong (calling the wrong methods, apparently). Can anyone tell me what I’m missing or have incorrect? Thank you!

$Playerreferences the KinematicBody2D parent node, and $Body references the Sprite node:

extends KinematicBody2D

export (int) var speed = 150

var velocity = Vector2()

func get_input():
	velocity = Vector2()
	if Input.is_action_pressed('ui_right'):
		velocity.x += 1
	if Input.is_action_pressed('ui_left'):
		velocity.x -= 1
	if Input.is_action_pressed('ui_down'):
		velocity.y += 1
	if Input.is_action_pressed('ui_up'):
		velocity.y -= 1
	velocity = velocity.normalized() * speed
func flip():
	if get_global_mouse_position().x - $Player.global_position.x:

func _physics_process(_delta):
	velocity = move_and_slide(velocity)
:bust_in_silhouette: Reply From: Adam_S

Your problem is this line:

if get_global_mouse_position().x - $Player.global_position.x:

“$Player” tries is to get a child node with the name “Player”, that is causing the error I think. Also you subtract the players position from the mouse position, which is not what you need.

So the correct code should be:

if get_global_mouse_position().x < global_position.x:

You could also shorten the flip() function like:

func flip():
    $Body.set_flip_h(get_global_mouse_position().x < global_position.x)

Makes more sense, and thank you for the shortened code as well!

Wolff | 2020-09-14 02:44