0 votes

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.

in Engine by (227 points)

1 Answer

+1 vote
Best answer

Collisions with TileMaps work differently than other nodes.
A TileMap has a TileSet, for which you can create tiles with this technique: http://docs.godotengine.org/en/latest/tutorials/2d/using_tilemaps.html
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.

by (29,092 points)
selected by

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.
enter image description here
RayCast2D are created using script. Sadly they don't return true using is_colliding() function.

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?

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?

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

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

if get_collider() != null:

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!

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.