How do I force the player to stay within the camera bounds when playing a side scroller? In my game the camera is continually scrolling through the level, I want the mechanic to work so that if the player hits the edge of the screen they cannot go any further.
I am assuming that the camera is always the same distance from the player (or that it is ortho). Set two colliders just outside of the camera’s view to the left and right. Attach the colliders to the camera. This way, when the camera pans, so does the colliders. Now the player will not be able to go off screen without hitting the colliders.
You will probably want to make the colliders triggers. You would want to do that to a) prevent enemies from being pushed by the colliders. b) prevent the player from standing still and letting the colliders physics attempt to push the player. That could cause some strange interractions.
When the trigger detects the player, it should just move the player to be right outside of the trigger again. With square triggers, this can be easily done:
if(other.tag == "Player")
{
//current position
float py = other.gameObject.position.y;
float pz = other.gameObject.position.z;
//place at new position
other.gameObject.transform.position = new Vector3(transform.x + .5f, py, pz);
}
This code takes the player and moves the player .5 along the x axis from the center of the collider. This assumes that the collider has an x axis scale of x. This will work regardless of how far into the collider the player moved. For the right side collider, just subtract .5f.