0 votes

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:
        $Body.set_flip_h(true)
    else:
        $Body.set_flip_h(false)

func _physics_process(_delta):
    get_input()
    flip()
    velocity = move_and_slide(velocity)
in Engine by (21 points)

1 Answer

+1 vote
Best answer

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)
by (1,437 points)
selected by

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

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.

Categories