RayCast2D detecting collision with TileMap - possible?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By websterek
:warning: Old Version Published before Godot 3 was released.

Hello
Is there anyway to detect collision of RayCast2D with TileMap?

Right now I have tile map with static body collider (with collision shape) and RayCas2D node. But after using is_colliding() function it’s returning me False.

:bust_in_silhouette: Reply From: Zylann

Collisions with TileMaps work differently than other nodes.
A TileMap has a TileSet, for which you can create tiles with this technique: Using TileMaps — Godot Engine (latest) documentation in English
During this process, collision shapes are added to tiles.

A TileMap doesn’t need a StaticBody or CollisionShape, tiles should have them already.

Next, if you want your RayCast2D to collide with the TileMap, you have to ensure they share a collision layer. For example, by default layer 0 is checked on both, so they should collide.

Edit: also, don’t forget to set enabled to true.

Hi. Thx for answer.
I have already tilesmap created like in this tutorial. Collision with normal RigidBody2d works very well. I think I don’t understand how RayCast2D work…

This is my Live Scene Tree, and runned scene with visible collisions.

RayCast2D are created using script. Sadly they don’t return true using is_colliding() function.

websterek | 2016-09-26 06:24

I tested a bit on a new project and I can raycast fine.

Two things I notice:

  1. Did you set collision shapes on the tiles you are raycasting into?

  2. Did you set the enabled property of RayCasts to true?

Zylann | 2016-09-26 12:33

Ok, this is a reason. I was thinking that rays are enabled at creation time. Now it’s working perfect! Thank you.
Ps. Is it possible to detect what tile was used?

websterek | 2016-09-27 06:49

You can know which tile was hit by getting the hit position and looking up the cell in the tilemap.
I usually do it this way:

if is_colliding():
	var hit_collider = get_collider()
	if hit_collider extends TileMap:
		var tilemap = hit_collider
		var hit_pos = get_collision_point()
		var tile_pos = tilemap.world_to_map(hit_pos)
		var tile_id = tilemap.get_cellv(tile_pos)
		# Do whatever you want

Zylann | 2016-09-27 18:38

I’d like to add that you can check if it is colliding like this:

if get_collider() != null:
     print(get_collider.name)

If you were to just type “if_colliding()” it wouldn’t detect that it is colliding and would pass even if colliding with something.

I don’t know if this was helpful, but whatever!

IronStudios | 2020-03-30 01:22

I think this will always tell you the name of the tilemap, and not the tile in particular?

Zylann | 2020-03-30 01:28