Why is my Raycast detection not working?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SuperSopwith
  onready var raycast = get_node("RayCast2D")


func _physics_process(delta):
	var playerposition = get_parent().get_node("Player").position
	$RayCast2D.set_cast_to(playerposition)
	var coll = raycast.get_collider()
	if coll.is_in_group("player"):
		print("TIS BUT A SCRATCH")
		look_at(playerposition)
		shoot()

The code is above. I’m getting the error “Attempt to call function ‘is _in _ group’ in base ‘null instance’ on a null instance” Does anyone know why this could be happening?

:bust_in_silhouette: Reply From: GameVisitor

As per the official documentation, get_collider() might return null in case of no collision:

    Object get_collider ( ) const

Returns the first object that the ray intersects, or null if no object is intersecting the ray (i.e. is_colliding returns false).

You need to check why the collision is not happening first.

Nice, thanks, I added in an if raycast.is_colliding(): and that solved the crashes, Thanks for your help!

SuperSopwith | 2020-09-04 21:34