Don't allow player to walk off edge of platform

I have a game where the floor is loaded in dynamically. So it could be of any shape and size but always made out of cubes. I want it so that if the player tries to walk off the edge it stops him like a wall.

Ways I have tried/thought of so far include:

  1. Multiple collision detectors… this seems excessive, 4 separate child objects of the player with box colliders, when one exits a collision with the floor it tells the player it can no longer move in that direction. This would be 4 new tiny objects, with box colliders, and a script attached to each one.

  2. A single collision detector underneath the character, and an invisible object that I have to manually put around the edge of all the floor objects that acts as a collider.

There must be an easier way, does anybody have any ideas?

You could raycast at an downwards angle from the character in your intended move direction. If you don’t hit anything, then you’re trying to walk off something, so you don’t do that.

Thanks for your advice, this is how I have done it, I needed to do separate raycasts to make sure it is the “edge” of the character that looks like its colliding. This may need some tidying up but works great thanks :slight_smile:

// Stop walking
var dir = transform.TransformDirection (Vector3.down);
      
 // Up
if(!Physics.Raycast (transform.position - new Vector3(0f, 0f, 0.255f), dir, 1))
       Vertical = -0.1f;
// Down
if(!Physics.Raycast (transform.position - new Vector3(0f, 0f, -0.255f), dir, 1))
       Vertical = 0.1f;
// Left
if(!Physics.Raycast (transform.position - new Vector3(-0.255f, 0f, 0f), dir, 1))
       Horizontal = 0.1f;
// Right
if(!Physics.Raycast (transform.position - new Vector3(0.255f, 0f, 0f), dir, 1))
       Horizontal = -0.1f;