Raycast not properly detecting

Godot Version

4.4

question

my raycast isnt properly detecting if there are objects in the way, returning <object.null> when there is an object in the way, here is a video of whats happening

if you have any questions do ask

edit: ok video quality sucks so heres the enemy script:
extends CharacterBody2D

@onready var navAgent: NavigationAgent2D = $NavigationAgent2D
@export var gunTemplate: PackedScene
@export var player : CharacterBody2D = null
@onready var rotatingNodes: Node2D = $rotatingNodes
@onready var playerCaster: RayCast2D = $inLineOfPlayer

var gun
@export var speed = 200.0
@export var health = 100.0

func makePath() -> void:
	navAgent.target_position = player.global_position

func _ready() -> void:
	gun = gunTemplate.instantiate()
	rotatingNodes.add_child(gun)
	gun.owner = self
	gun.position = Vector2(200,0)
	gun.scale = Vector2(3, 3)
	if not player:
		player = %player

func _physics_process(delta: float) -> void:
	playerCaster.target_position = player.position
	rotatingNodes.look_at(player.global_position)
	#if playerCaster.is_colliding():
	var direction = to_local(navAgent.get_next_path_position()).normalized()
	velocity = direction * speed
	move_and_slide()

func _on_timer_timeout() -> void:
	#if playerCaster.is_colliding():
	makePath()

func _on_firerate_timeout() -> void:
	gun.shootBullet()
	playerCaster.force_raycast_update()
	print(playerCaster.get_collider())



func _on_bullet_collider_bullet_collided() -> void:
	health -= 20
	if health < 0:
		add_sibling(gun)
		queue_free() # Replace with function body.

generally if the text in output is small its saying <object.null> and when its not its detecting either tilemap or player (latter is quite rare)

RayCast2D.target_position is relative to the raycasts position, i.e., in local coordinates: RayCast2D — Godot Engine (stable) documentation in English.

To convert a position to local coordinates you can use to_local.

Also make sure that you are calling force_raycast_update in a physics frame. But I think you don’t need it at all.

You can format your code with ```. This makes it easier to read.

2 Likes

Along with pmoosi’s advice, turn on visible collisions and see where the raycast is pointing and with what it is colliding.

Hi, you can turn on visible collisions to see your raycasts