Look_at() not rotating sometimes

Godot Version

v4.2.2.stable.official [15073afe3]

Question

I’m trying to get an arrow to point towards a position raycasted from the cursor. It works if I point my cursor at anything but the floor or any flat ground for some reason.

Here’s it working correctly:

and then not:

	if cursor_raycast:
		var target_position = cursor_raycast.position
		var target_normal = cursor_raycast.normal
		var new_position = (target_position + (2 * target_normal))
		arrow.position = new_position
		if arrow.position != target_position:
			arrow.look_at(target_position, Vector3.UP)
		else:
			print("Same position!")

I figured it out finally. I was getting the error “Up vector and direction between node origin and target aligned, look_at() failed”. Here’s my modified code:

	if cursor_raycast:
		var target_position = cursor_raycast.position
		var target_normal = cursor_raycast.normal
		var new_position = target_position + (1 * target_normal)
	
		arrow.position = new_position
		
		if not arrow.position.is_equal_approx(target_position) and not target_normal.is_equal_approx(Vector3.UP):
			arrow.look_at(target_position)
		else:
			arrow.rotation = Vector3(deg_to_rad(-90), 0, 0)
1 Like

Yeah that error gets me sometimes. Here’s another way to address it: you can optionally provide a custom ‘up’ to look_at, so instead of 0,1,0 it’s whatever you want. In your code where you added the check, instead of just setting the rotation in the case of ‘vectors too close’, give it that optional second argument for custom up and use a vector like 0,0,1

Alternatively, I suspect you could take the camera’s basis X component (the local right vector), and then take a cross product between that and the cursor_raycast normal, and that resulting vector should be a consistently valid ‘up’. I have not tested that with your code but I believe it would work ok.