2D Camera boundaries C#
I'm making a 2D game that and the Y values for the camera need to be restricted to the edges of the map. I have looked at a lot of other questions regarding the 2D Orthographic camera restriction and I have NO idea what they are talking about. Please note I am new to C# and Unity, so please make an explanation as simple as possible.
Answer by Jason2014 · Nov 20, 2016 at 11:56 AM
If you want "boundaries" you can try Mathf.Clamp which is great for values limitting. Insert this code to Update function.
transform.position = new Vector3
(
Mathf.Clamp (transform.position.x, minimumBoundary.x, maximumBoundary.x),
Mathf.Clamp (transform.position.y, minimumBoundary.y, maximumBoundary.y),
transform.position.z
);
Minimum and maximum boundary are variables of type Vector2. You can declare them as public for easy adjustment while gameplay.
Answer by jonavuka · May 06, 2017 at 03:12 PM
I would avoid clamping because it causes flickering, I would just check the next position and avoid moving it to that position if it leaves your bound. For example I used the follow target script and restricted the new position if it leaves the bounds as such:
if(newPos.x > minX && newPos.x <maxX && newPos.y>minY && newPos.y<maxY)
transform.position = newPos;
By doing that it causes no flickering because it doesn't update the position and then clamp it to a the boundary follow, it just prevents from updating the out of bound position entirely.
Your answer
Follow this Question
Related Questions
Orthographic camera size not changing 0 Answers
Orthographic Camera Appears to be Only Rendering Top Half of the Screen? 0 Answers
Giving The Illusion of Depth in an Orphographic Game 0 Answers
Persistent circle on Unity Orthographic Camera 0 Answers
Camera Orthographic size, 2D boundaries for camera 0 Answers