How to detect if CharacterBody2D has reached the edge of the floor

I have this simple setup with a platform and a slime:

I want to program slime to slowly move one way and once it reaches the edge of the platform - change direction and go to the left. Is there a way to do this?

I know I can put 2 invisible collision areas on both sides and mask them to interact only with the slime but TBH I don’t really like this solution and would like something I can reuse easier.

From what I know, one way to do this would be pathfinding. If you reuse the tilemap, or class the script, you could reuse it.But this would be overkill.

Maybe you could use if statements that change the slime’s direction if it reaches the edge.
You would just need to know or look at the positions of both edges.

Might be annoying, but simple…and not hard to reuse

This is exactly what my question is about. I’m looking for ways to do exactly this.

For vars:

var speed:int = 10
var dir: Vector2

For the if statements:

func _process(_delta):
if $Enemy.position.x <100:
dir = Vector.RIGHT
if $Enemy.position.x > 300:
dir = Vector.LEFT

for the movement:

func _process(_delta): #same process function
velocity = speed * dir
move_and_slide()

This should make the enemy move left and right accordingly to the position. Note that these are just example vars, you can fully customize them, fitting to your game.

This is not reusable at all. I would like to be able to throw a CharacterBody2D onto any surface and once it reaches the edge of it, change its direction, setting up x coordinate ranges manually is not what I wanted at all. I need to somehow get tile beneath the body then get its neighbor tile, then if it exists and has collider do nothing, otherwise - allow body to go to the edge of current tile and change direction. I was able to find tile index of the tile below and tile index of the next tile at current direction but I’m not sure how do I get info about that tiles collider, global coordinates and size.

check RayCast2D

image

Area2D still collide with platform, but when RayCast2D lost is_colliding() is false then change direction

like this

Oh, now I understand. Sorry for my mistake

Yes, this is exactly what I needed. Did not realize there is this component. Thanks!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.