- Home /
How can a character not move out of box collider's bounds?
The character has a collider too, not sure how to script this?
Delete that box collider and replace it with two smaller colliders. Put one of these colliders on the left side of the boundary and the other on the right side. These will act as walls to prevent the player from going past them.
Answer by Klarzahs · Jan 08, 2019 at 10:34 AM
Hi,
You can either check whether the character is in the bounds of the collider, or you can reset it to the last known position after colliding.
The first one can be achieved like this:
public GameObject colliderGO;
public GameObject player;
public void BlockPosition(){
BoxCollider box = colliderGO.GetComponent<BoxCollider>();
Vector3 size = box.bounds.size;
Vector3 pos = colliderGO.transform.position;
float maxX = pos.x + size.x/2f;
float minX = pos.x - size.x/2f;
//reset the players transform if it is below minX or above maxX
}
For the other option you'll need to save the players position in "OnCollisionStay()" and reset the players transform on "OnCollisionExit()". Take a look at the collision matrix at the Collision Manual, to see which components are necessary.