- Home /
Question by
Usless_Vay · Mar 01, 2021 at 05:05 AM ·
unity 2dcamera-movement
Make camera check for multiple things at once in Unity 2D
I need to check for the X axis AND the Y axis at the same time, and maybe chop the else if tree.
public class CameraFollow : MonoBehaviour
{
public Transform Player;
void FixedUpdate ()
{
if (Player.position.x >= 12.1f) {
transform.position = new Vector3(12.1f, Player.position.y, transform.position.z);
}
else if (Player.position.x <= -0.2f) {
transform.position = new Vector3(-0.2f, Player.position.y, transform.position.z);
}
else if (Player.position.y <= -1.18f) {
transform.position = new Vector3(Player.position.x, -1.18f, transform.position.z);
}
else if (Player.position.y >= 4.15f) {
transform.position = new Vector3(Player.position.x, 4.15f, transform.position.z);
}
else {
transform.position = new Vector3(Player.position.x, Player.position.y, transform.position.z);
}
}
}
For example, I need the camera to check if X is greater then a certain number as well as if Y is less then a certain number, and I want that to be better then an if else tree.
Comment
Best Answer
Answer by Ermiq · Mar 01, 2021 at 06:02 AM
Vector3 camPos;
void FixedUpdate()
{
camPos.x = Mathf.Clamp(Player.position.x, -0.2f, 12.1f);
camPos.y = Mathf.Clamp(Player.position.y, -1.18f, 4.15f);
camPos.z = transform.position.z;
transform.position = camPos;
}
Your answer
Follow this Question
Related Questions
Help with a 2d camera Controller 1 Answer
Follow camera in 2d game 2 Answers
I want to lerp between different changing values 1 Answer
Keeping UI Element To Game Object When Camera Moves 2 Answers