Detect collision with some tiles from an tilemap

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

Good day,

i have a problem with the detection of collisions in a 2D top down project.

The player is a KinematicBody2d with the movement via move_and_collide. In the map the player is on his own PB2D layer and mask. The tiles in the tilemap have all some CP2D and the tilemap is on its own layer and mask.

The collision detection works if both player and tilemap are on the same layer but then the player cant “go through / go over” the tile.

I want is to detect if the player is moving over the tile with the name or number x and then cut his move speed in half.

Is there away to make this possible or do i have to rethink anything?

The code can be found GitHub - Fedena22/NGP: Next game Project

Thanks for your help.

You can get Player position in Tile space with function in TIleMap class: world_to_map, e.g.: var playerTilePosition = TileMap.world_to_map(Player.position).
Then you need to check if playerTilePosition has same index as a tile that should slow down Player, e.g.:
if TileMap.get_cellv(PlayerTilePosition) == “YourSlowDownTIleIndex”:
playerVelocity = playerVelocity/2

pospathos | 2018-11-10 00:20

Becouse you are using KinematicBody2D, on tiles that should slow down Player you should use Area2d, and then check with: body_entered().

pospathos | 2018-11-10 00:26

:bust_in_silhouette: Reply From: iron_weasel

move_and_collide is going to make the KinematicBody2d stop as if the other thing is solid so you need a different method.

In your example you have an obstacle that changes behavior of the player, but does not stop it in its tracks. If I was doing this I would add an additional child (probably Area2D) that I would use as a sensor. I would add a new collision layer bit like “SlowDown” and I would mask the Area2D to detect it. I would then use a signal like body_entered to detect when the player is touching that object and halve the speed or set a flag or however you want the behavior to flow.

Thanks helped me a lot

Kentaro | 2018-11-20 19:10