problem detecting collision with raycast

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

I have an enemy that moves and detects the ground and you look like them, it has two lines that detect if an enemy is approaching, everything works fine until the enemy collides with a tilemap block and then I get this error.

Trying to assign a value of type ‘TileMap’ to a variable of type ‘KinematicBody2D’.

var player: KinematicBody2D = null

var velocity = Vector2 ()
var distance = Vector2 ()
var speed = 120
var direction = Vector2 (-1.0)

func _physics_process (delta):

.apply_gravity (true, delta)
var t = self.transform
t [2] .x + = 5 if address.x == 1 else -5

if! test_move (t, Vector2 (5.2)):
address.x = -1
$ Spr.flip_h = false

elif! test_move (t, Vector2 (-5,2)):
address.x = 1
$ Spr.flip_h = true

if is_on_wall ():
address.x = 1 if address.x == -1 else -1
$ Spr.flip_h = false if $ Spr.flip_h == true else true



if $ Left.is_colliding () and! player:
player = $ Left.get_collider () 
direction.x = -1
$ Spr.scale = Vector2 (-direction.x, 1)
emit_signal ("attack", "Attacking")
elif $ Right.is_colliding () and! player:
player = $ Right.get_collider ()
direction.x = 1
$ Spr.scale = Vector2 (-direction.x, 1)
emit_signal ("attack", "Attacking")


if! $ Left.is_colliding () &&! $ Right.is_colliding ():
player = null

I BELIEVE THAT THE ERRO IS GIVEN BY THE RAYCAST COLICIONA WITH THE TILEMAP AND THIS IS ASSIGNED TO THE VARIABLE PLAYER BUT THIS ONLY ALLOWS KINEMATICBODY2D, HOW IT COULD BE SOLUSED!

:bust_in_silhouette: Reply From: tastyshrimp

I believe that you are right and the reason is that the Raycast will hit any object in the same collision layer as it, be it a player or a tilemap or any other object you add in the future.

Based on that, I believe you have 2 possible solutions:

  1. If the tilemap should never block the “vision” of the enemy, you can change everything that should be detected by the raycast and the raycast itself to a different collision layer.

  2. Add a check by the kind of object or in which group the object is when the collision happens and ignore everything that is not the player, in this case you can block the vision of the enemy with different objects.

Bonus option, 1 or 2 should solve most of your cases, but if you have some very specific case that you cannot make it work with either, you can cast the Ray towards where it should using the Space and whenever you hit something that should be bypassed you add it to the ignore list (3rd parameter of the intersect_ray method) and cast it again. I would avoid this method if possible due to the possibility of casting too many rays in a single physics loop, but the possibility exists.

I would look into the Ray-casting Space anyway if you need something more complex.