Trying to get an enemy to look at the player

Godot Version



<I have three scenes: Player, Mob, and Main. I am trying to use get_node() to assign the players position to a var so I can use look_at() to get the enemy to look at the player.
my code:
`extends CharacterBody2D

const speed = 400
@onready var Player = preload(“res://Player.tscn”)
@onready var pos = get_node(“/root/Player/player”).position

func _process(delta):
position += transform.x * speed * delta`

my scene tree for the Player looks like this:

thanks for the help.>

Getting the position on ready will only get the position once, when the game starts, and it will never update. If you want the position to update, get it every frame in the process function. Also, you should probably use _physics_process and move_and_slide if you’re using a CharacterBody2D.

1 Like

having this logic in _process() is as far as I understand OK.

but within this process function, you should have a vector2/position reference to your target (player) so it updates the position every frame.
something like
func _process(delta):
var target = Player.position

1 Like

I totally would have ran into that wall head first XD, but I am now realizing I didn’t specify my problem. I am getting a null instance error, any ideas on that?

Thanks again!

What does it say? (the error) perhaps you used my code literally. Player.position (Player) should be a reference to the player (Character2D) node.So probably get_node(“/root/Player

What does your scene look like? Is it Main as root node and both Player and Mod beneath it?

My code is above, here is the error:
E 0:00:00:0835 @ _ready(): Node not found: “/root/Player/player” (absolute path attempted from “/root/Node/mob”).
<C++ Error> Method/function failed. Returning: nullptr
<C++ Source> scene/main/node.cpp:1636 @ get_node() @ _ready()

My current path: /root/Player/player
I’ve tried a bunch of different paths, this is just the last one I tried.

I have just the three scenes: Player, Main, and Mob. Player and Mob are both linked to the Main scene.

You should get the player node like this:
@onready var Player = get_node(“…/Player”)

You are on the same level, so you need to go back one node and then select the Player node

didn’t work, I am just going to start from scratch.