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)