Raycast2d not working

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DudeGames

I am trying to use a raycast2d added to the enemy to see if it collides with the player and if it is then tell the enemy to shoot. The problem is that the raycst2d is not colliding at all I set it to enabled and set the cast_to so it should collide but it doesn’t. Is there another way to make a targeting system for an enemy that is an airplane moving in the x axis in the top part of the screen and shooting down or am I missing something that makes the raycast2d not working?
This is the code for cheking if the raycast is colliding the cast_to is set from the ui :

func shoot():
var bomb=Bomb.instance()
if $RayCast2D.is_colliding():
	var object= $RayCast2D.get_collider()
	print (object)

pass
:bust_in_silhouette: Reply From: fossegutten
  1. It is disabled by default, it seems you checked that already.
  2. You should check if $Raycast2D.is_colliding() before accessing collider, or you can get errors.
  3. Did you check that your collision layers are in order? Raycast2D has its own collision mask, it doesnt inherit from the parent.

Hope this helps :slight_smile:

I don’t know how to check if the collison layers and masks are in order , everywhere it says that is the first layer. And in the code I wrote first to see if the raycast2d is colliding then to print the object but it doesn’t print anything. Is there a problem if the raycast2d is a child of an area 2d ?

DudeGames | 2019-06-24 16:26

There shouldnt be any problem with the Raycast being a child of Area2d. It can be a child of anything. It sounds like it is not colliding at all. Could be that node is not enabled, and it could also be wrong collision layer.
I recommend you to check out a tutorial on Raycast2D and also collision mask / layer. Here is one for Raycast2D:
https://www.youtube.com/watch?v=esZdJegvANc

fossegutten | 2019-06-27 13:25

:bust_in_silhouette: Reply From: drorya

I had the same problem just now, so for others who were looking for a solution, here’s mine:
first, I tried to see if the RayCast2D I created was responding to any layer (other than the players’).
And it worked, the RayCast2D responded when I set its’ collision to different layers.
Next, I checked my player’s collision settings, and didn’t find any problem there.
I decided to make a risky move, and deleded the player’s Node from the main scene (for me it was level1) , and re-attached it to the same place.
AND IT WORKED!
I still don’t know what was the initial problem, but at least I found a solution.
¯_(ツ)_/¯
hope I could help someone :slight_smile:

Thanks !

Same solution, I deleted the AnimateSprite and re-attached

Jorge | 2020-06-26 22:35

1 Like

Yep, the same solution here. Thanks!