This article shares the specific code for Unity3D to realize camera lens movement and limit angles for your reference. The specific content is as follows
The camera lens follows the mouse and limits the moving angles up, down, left and right
public class ViewFromCream : MonoBehaviour { public int speed=5; public Vector3 vect; private float xcream; private float ycream; public void Update() { CreamView(); } private void CreamView() { float x = ("Mouse X"); float y = ("Mouse Y"); if (x!=0||y!=0) { LimitAngle(60); LimitAngleUandD(60); (-y * speed, 0, 0); (0, x * speed, 0, ); } } /// <summary> /// Limit the camera's left and right viewing angles /// </summary> /// <param name="angle">angle</param> private void LimitAngle(float angle) { vect = ; //The current camera's x-axis rotation angle (0~360) xcream = IsPosNum(); if (xcream > angle) = (angle,,0); else if (xcream < -angle) = (-angle, , 0); } /// <summary> /// Limit the angle of the camera's upper and lower viewing angles /// </summary> /// <param name="angle"></param> private void LimitAngleUandD(float angle) { vect = ; //The current camera y-axis rotation angle (0~360) ycream = IsPosNum(); if (ycream > angle) = (, angle, 0); else if (ycream < -angle) = (, -angle, 0); } /// <summary> /// Convert angle to angles of -180~180 /// </summary> /// <param name="x"></param> /// <returns></returns> private float IsPosNum(float x) { x -= 180; if (x < 0) return x + 180; else return x - 180; } }
Explain the IsPosNum method
The reason why I want to convert the obtained Euler angle to between -180°-180° is because in obtaining the values of the x-axis and y-axis in eulerAngleOnly 0-360, no negative numbers, then this will complicate our judgment of angles. If the left and right angles are limited to -60-60, then we need to judge whether the angle exceeds 300 degrees or exceeds 60 degrees. Obviously, the angle exceeds 300 degrees must exceed 60 degrees, so additional conditions are required to make judgments; therefore, it is more convenient to convert the obtained value!
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.