- Home /
Keep character inside camera bounds
Hi,
What would be the best way of ensuring the character can not leave the bounds of the camera? I am creating a game where the camera only ever scrolls forward, and I want to prevent the character from going backwards.
Would I perhaps attach some kind of box collider to the camera or something?
Answer by skovacs1 · Oct 29, 2010 at 02:29 PM
If your camera is scrolling forward at a set rate, attaching a child box collider is a valid solution, but it depends on OnTriggerExit or OnCollisionExit firing to ensure it works. Alternatively, attaching child planes or boxes outside the camera's view would essentially have the same effect, but would work OnTriggerEnter or OnCollisionEnter. Another solution when the camera is scrolling forward at a set rate is to check the character's screen/viewport position and then correct if they are off the screen, but this requires at least one matrix multiplication every time the screen/viewport-world position is calculated.
A different approach if the character controls camera scrolling forward only would be to check the character's screen coordinates when they move backwards. When the character moves backwards, check if their position exceeds the allowable position and then correct. Rather than performing the camera calculations all the time, you really only need to register the world position of the camera's bounding volume at the character's depth when they change from moving forward to moving backwards, so this implementation can actually be far cheaper than depending on collisions.