Rotating RayCast2D misses targets

Godot Version

4.2.1

Question

A character spawns a detection node on its position every 0.2 seconds, nodes despawn after 2 seconds. Detection nodes have collision layer set to 8.

Following code should detect if ‘enemy’ can directly see detection nodes and if yes, turn towards the latest.

func update(delta):
	if state_active and active_target:
		attack(delta)


func _on_fov_body_entered(body):
	if state_active == true:
		if body.is_in_group("player_step"):
			enemy.raycast.target_position = enemy.raycast.to_local(body.global_position)
			if enemy.raycast.is_colliding():
				
				if enemy.raycast.get_collider().get_collision_layer_value(8):
					
					active_target = enemy.raycast.get_collider().global_position
					print(active_target)
						

func attack(delta):
	if state_active and active_target:
		direction = active_target - enemy.global_position
		enemy.global_rotation = lerp_angle(enemy.global_rotation, direction.angle(), delta)

Instead, it completely misses most of the detection nodes.
Disabling rotation helps proper targeting, so I believe that somehow RayCast2D misses its targets.
Have already tried increasing nodes’ collision boxes.

That “to_local” is suspect to me, typically rays are cast in global space so all positions should be in global and not local…

Also this sounds like a job for ShapeCast2D

1 Like

I am tracking active_target position in debug, so I know it can’t be it.

The problem is rotation, as it works fine if I disable it. It’s not even that fast.

For some reason it doesn’t pick the newest detection node as target, when the ray caster rotates.

ShapeCast may work, I need to read about it first

There is also the force raycast update function, maybe that could salve your missing collision issue.

1 Like

This.

Forcing update right after setting raycast target to newest node was the solution. It now works really smooth.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.