RayCast follow does not work correctly with look_at() function

Godot Version

Godot Engine v4.3.stable.mono.official.77dcf97d8 - https://godotengine.org

Question

I’m trying to check whether the player is visible on the monster’s camera view, but the beam launch doesn’t work properly at all and I can’t find the source! After displaying the collision boxes in the debug view, I observe that my raycast never points to the player’s position even though the condition for performing the task is true, it just moves to a position that seems random.
Here’s my code:

func tick(actor, _blackboard):
	if actor.is_node_ready():
		
		var position2d = actor.CAM.unproject_position(actor.PLAYER.position)
		if position2d < Vector2(get_viewport().size) and position2d > Vector2(0,0): 
			print("In camera view")
			var from = actor.CAM.project_ray_origin(get_viewport().size/2)
			var to = from + actor.CAM.project_ray_normal(position2d) * 1000
			var raycast :RayCast3D = actor.RAYCAST
			raycast.target_position = to
			if raycast.get_collider() == actor.PLAYER:
				return SUCCESS
			print(to)
	return FAILURE

I would use global_position just to be safe.

Also i have seen problems with Raycast3d nodes needing to be force updated. You can also formulate a raycast query as an alternative.

Thanks for the help but doesn’t work, here is the visual of the problem:

EDIT: I’ve found the source of the problem, the problem only occurs if I perform a look_at() on the CharacterBody3D (RayCast3D parent). But I don’t know why

There are conditions to using look_at.

Other than pointing at something that isnt exactly the player it looks mostly correct. There is one point where it seems to bug out, but this could be due to the conditions of look_at and the invisible self?

Btw look_at makes -z axis to be forward, it kind of looks like the raycast is not pointing in the -z direction.

1 Like

Yes, it’s definitely the “look_at()” that’s the problem, when I use it only on visual nodes and the camera, the problem no longer exists. I think it’s due to the fact that the look_at() changes the z axis, I didn’t know that, thank you! But how do you turn the CharacterBody3D to a position? Smoothly if possible.

Are you rotating the raycast (directly or indirectly via parent) but using a target based in world space? If the raycast is being set to look at something it just needs to have a target like (0,0,-range). If look_at seems backwards there’s a parameter in look_at to flip the z direction that might fix it.

Yes, that’s it! (indirectly)