Why are my raycasts facing down despite me not programming them to that

Godot Version

Godot 4.5.1 stable

Question

I have been trying to program enemy AI. However for some reason the raycasts are always facing down no matter what despite not being programmed to face down nor are they that direction in the editor. I can’t work out why this is happening

extends CharacterBody3D

@onready var ray = $RayCast3D
const bullet = preload("res://bullet.tscn")
@onready var fireNow = preload("res://soldier.tscn")
var canFire = false
#var can_fire: bool = fireNow.playerSpotted
func _ready() -> void:
	pass
func _physics_process(delta: float) -> void:
	var target = Vector3(Autoload.player.position.x, Autoload.player.position.y, Autoload.player.position.z)
	var direction = position + target
	var direction_to_Player = target - global_position
	rotation.z = lerp_angle(rotation.z, atan2(direction_to_Player.x, direction_to_Player.y), delta/10)
	ray.target_position = ray.to_local(direction)
	if Autoload.playerSpotted:
		pass
	#var targetPosition = ray.direction_to(Autoload.player)
	if $".." in get_tree().get_nodes_in_group("canShoot"):
		fire()
		
	if Input.is_action_just_pressed("check"):
		print(direction_to_Player)
func fire():
	var shoot = bullet.instantiate()
	#print("Fire!")
	add_sibling(shoot)

Thank you

You’re mixing global_position with local position, so the calculated direction might not be what you think it should be.
Also, I don’t see you using the ray for anything. How did you even deduct that it’s facing incorrect direction?

1 Like

I didnt notice that but what do you mean I didnt use ray for anything?

I think you are calculating direction wrong. You want to subtract the enemy’s position from the player’s position instead of adding them. Also, I think the rotation of the enemy might affect the raycast target position since the raycast is a child of the enemy.

Yeah I did fix that. It works better however it seems to sink down after a while