TheLost Lostit TheLost Lostit - 4 months ago 35
C# Question

How can i prevent player from walking out of the terrain edges?

In this case my terrain Transform is: Position X = -250 Y = 0 Z = -250
Rotation 0 0 0 and Scale 1 1 1

The terrain resolution is Width 500 and Length 500 and Height 600

So if i have a ThirdPersonController or a spaceship in some Height when i move the objects to the Terrain edges i want them to stop there and not to continue out of the terrain area.

How can i calculate it in c# script and prevent from the objects to leave the terrain borders ?


  1. Create an empty game object and attach a BoxCollider to it.
  2. Configure the BoxCollider: Center: 0, 0, 0. Boundary: 500, 600, 500. IsTrigger: On
  3. Position it properly on the editor. It will be your restriction area.
  4. Attach a script to it, in side your script insert this method

OnTriggerExit(Collider c) { /* Your code */ }

Your code will be executed every time a collider leaves your BoxCollider. If that is your player, reset it position so that it is inside the restriction area or you could use physics force to pull him back inside.