This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

Hey
Recently, I did the player's eye following mouse using this piece of code:

# Nodes Referencing
onready var eyes = get_children()[0]

# Constants
const MAX_EYE_UP = -3

# Variables
var max_dist = 2

func _process(_delta) -> void:
    # Eyes following mouse
    var mouse_pos = get_local_mouse_position()
    var dir = Vector2.ZERO.direction_to(mouse_pos)
    var dist = mouse_pos.length()
    if mouse_pos.y < MAX_EYE_UP:
        dir.y = 0
    eyes.position = dir * min(dist, max_dist)

Basically, a vector points to the mouse, and the node follows, but with a max distance.

However, I'd like the enemy's eye following player using the same logic. I tried using length() and distance_to() functions, to calculate the distance between the enemy's eyes and the player, but the node of the eyes sometimes doesn't follow the player.
My actual logic:

# Nodes Referencing
onready var eyes = get_children()[0]
onready var player = get_tree().get_current_scene().get_node("Player")

# Variables
var max_dist = 10 # random value

func _process(_delta) -> void:
    # Eyes following player
    var dir = Vector2.ZERO.direction_to(player.position)
    var dist = eyes.global_position.distance_to(player.global_position)
    eyes.position = dir * min(dist, max_dist)
Godot version latest
in Engine by (27 points)

1 Answer

+1 vote
Best answer

In your player logic, your code works in local space, relative to the player:
get_local_mouse_position() is relative to the player, and you used Vector2.ZERO for some reason but I assume that's also because the eyes of the player are at the origin of the player too, so their relative position would be zero.

In your enemy logic however, player.position seems to be the global position of the player. So you can't use Vector2.ZERO as the position of the eyes of the enemy.
In fact, the line after you are using the global position of the eyes!
So maybe you should change your code to:

var eyes_pos = eyes.global_position
var dir = eyes_pos.direction_to(player.position)
var dist = eyes_pos.distance_to(player.global_position)
eyes.position = dir * min(dist, max_dist)
by (29,510 points)
selected by

oh yeah! thx!

I switched the parameter of direction_to (2nd line) and now it worked!

var dir = eyes_pos.direction_to(player.global_position)
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 Frequently asked questions and 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 [email protected] with your username.