RayCast3D look_at issue

Godot Version



Hi, I’m trying to make a 3D character (NPC), that is a bit smarter. I’ve made a custom “vision cone” and attached it to the NPC. When the player enters this Area3D, I want to point a RayCast3D at the player every X seconds and tell if there is something in the way. I have implemented everything but I still have one major issue: The ray.look_at(player_position, Vector3.UP) is not working as I was expecting. It points the ray in another quadrand. I can see it moving, but it’s all wrong, either it has the Y axis inverted or the X axis inverted. I’ve tried to change the value of the UP Vector but I just can’t make this work. I’ve rotatated the player_position 90deg around the X axis and that’s how far i’ve got to success. Now the ray follows the player up and down but not left-right. How can I achieve this type of thing? Am I missing something about the look_at function? I thought it was straight forward, but it turs out it’s the most difficult thing I’ve had to do.

Here’s the relevant part of my code:

@onready var ray = $VisionRayCast
# .... more code ...

func _on_vision_timer_timeout():
	if not playerInVisionField:
	# Get the global position of the player
	var player_position: Vector3 = player.global_transform.origin
	ray.look_at(player_position.rotated(Vector3(1,0,0), deg_to_rad(-90)), Vector3.UP)
	if ray.is_colliding():
		var collider = ray.get_collider()
		if collider.name == "Player" or collider.get_parent_node_3d().name == "Player":
			chasePlayer = true

Ohh… I’ve just figured out why my code was’t working…

The RayCast’s Target position was set to (0, -100, 0) instead of (0,0,-100). The problem was that I was just using the wrong target position all this time and I’ve wasted more time that I’m willing to admit. I’ll just leave my question and answer here in case that another poor soul does the same mistake as me. Have a nice day and happy coding!