Cant get an object to look at the player

Godot Version

4.7.2

Question

I cannot for the love of god get this object to simply look at the player. I’ve tried so many different things and each time I get an error that says “Invalid access to property or key ‘global_position’ on a base object of type ‘null instance’.”

@onready var player = get_parent().get_node("player")

func _ready() -> void:
	pass

func _process(delta: float) -> void:
	if fov.turret_active == true:
		look_at(player.global_position)

This node cannot find the player node. You could try using an @export variable instead of pathing to the player.

when does your turret_active change? If you are using some kind of sight detection that uses collision/areas you could keep a reference to the player from that.

I have an area connected to the turret that detects when the player enters it. Its just to turn the turret on and off when the players near it.

@onready var fov := $"../FOV"
extends Area2D

@export var turret_active = false

func _on_body_entered(body: CharacterBody2D) -> void:
	turret_active = true

func _on_body_exited(body: CharacterBody2D) -> void:
	turret_active = false

So that body gets passed into entered/exited can be the player. You can keep a reference to that instead of true/false

extends Area2D

var found_player: CharacterBody2D = null

func _on_body_entered(body: CharacterBody2D) -> void:
	if body.name == "player": # better to use `is_in_group` or `is` with a class_name
		found_player = body

func _on_body_exited(body: CharacterBody2D) -> void:
	if body == found_player:
		found_player = null

Then your player script can check if the found player is valid, and look at them.

func _process(delta: float) -> void:
	if fov.found_player:
		look_at(fov.found_player.global_position)

You’re a life saver, tysm!