- Home /
Restrict Movement on the Y-Axis When Using LookAt.Transform?
I'm trying to have the Camera Rotate around a player character when you press the arrow keys. Currently if you move up and down the camera will go all the way up rotate and then start moving downward on the opposite side of the player. I want it so the camera stops at a certain angle in either direction on the y.
Current Code that doesn't work:
public class CameraScript : MonoBehaviour {
public Transform target;
public float turnSpeed = 3.0f;
public float rotationX = 0.0f;
public float rotationY = 0.0f;
public float min = -50.0f;
public float max = 50.0f;
// Update is called once per frame
void Update () {
rotationX = Input.GetAxis("Horizontal") * turnSpeed;
rotationY = Input.GetAxis("Vertical") * turnSpeed;
rotationY = Mathf.Clamp(rotationY, min, max);
transform.LookAt(target);
transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z);
transform.RotateAround(target.transform.position, Vector3.up, rotationX);
transform.RotateAround(target.transform.position, Vector3.right, rotationY);
}
}
Answer by M-Hanssen · Apr 18, 2016 at 09:57 AM
You were on the wright track, but missed a few things:
Vector3.right should be transform.right
You shouldn't clamp the Rotation by the min and max of itself but the min and max of the current angle. See my comment that it's not always safe to use euler angles for angle measurements, but in this case I'll save you the headache of Quaternions ;-p
I modified your script so it is clean and ready to use:
public class CameraScript : MonoBehaviour
{
public Transform Target;
public float TurnSpeed = 3.0f;
public float RotationHorizontal;
public float RotationVertical;
public float Min = -50.0f;
public float Max = 50.0f;
// Update is called once per frame
protected void Update()
{
RotationHorizontal = Input.GetAxis("Horizontal") * TurnSpeed;
RotationVertical = Input.GetAxis("Vertical") * TurnSpeed;
// Calculate the current angle in degrees (Not very reliable using Euler angles in all situations. Keep this in mind!)
float verticalAngle = transform.localEulerAngles.x > 180 ? transform.localEulerAngles.x - 360 : transform.localEulerAngles.x;
// Set verticalRotation to zero if min or max value is reached
if (verticalAngle > Max && RotationVertical > 0) RotationVertical = 0;
else if (verticalAngle < Min && RotationVertical < 0) RotationVertical = 0;
transform.LookAt(Target);
// Rotate the camera
transform.RotateAround(Target.transform.position, Vector3.up, RotationHorizontal);
transform.RotateAround(Target.transform.position, transform.right, RotationVertical);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612075033im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to make FPS Camera bounce when walking 1 Answer