功能简介:
unity的3d场景中,设置3d物体和2dUI,随鼠标移动,向左/右旋转,带角度限制;
1、获取鼠标位置
float mouseX = Input.GetAxisRaw("Mouse X")
float mouseX = Input.GetAxisRaw("Mouse X");
2、设置物体的左右朝向
transform.Rotate(- Vector3.forward * mouseX * rotateSpeed);
transform.Rotate(Vector3.forward * mouseY * rotateSpeed);
transform.Rotate(-Vector3.forward * mouseX * rotateSpeed);transform.Rotate(Vector3.forward * mouseY * rotateSpeed);
3、限制物体角度
(1)3d场景中,限制Y
float angleY = transform.eulerAngles.y;
if (angleY <= 35) angleY = 35;
transform.eulerAngles = new Vector3(transform.eulerAngles.x,angleY, transform.eulerAngles.z);
(2)UI场景中,限制Z
float angleZ = transform.eulerAngles.z;
if (angleZ >= 150) angleZ = 150;
transform.eulerAngles = new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,angleZ);
//示例,限制X方向float angleX = transform.eulerAngles.x;if (angleX <= 45) angleX = 45;transform.eulerAngles = new Vector3(angleX,transform.eulerAngles.y,transform.eulerAngles.z);
4、完整功能代码
脚本直接挂到目标对象身上即可。
这里直接把设置物体和设置UI的代码放同个脚本中,根据需要进行保留删除。
public float rotateSpeed =10f;public void Update(){RotateItem();
}/// <summary>
/// 旋转物体
/// </summary>
private void RotateItem()
{float mouseY = Input.GetAxisRaw("Mouse Y");float mouseX = Input.GetAxisRaw("Mouse X");transform.Rotate(-Vector3.forward * mouseX * rotateSpeed);transform.Rotate(Vector3.forward * mouseY * rotateSpeed);LimitAngle();LimitImgAngle();
}/// <summary>
/// 限制场景中物体的Y角度
/// </summary>
private void LimitAngle()
{float angleY = transform.eulerAngles.y;if (angleY <= 15) angleY = 15;else if (angleY >= 165) angleY = 165;transform.eulerAngles = new Vector3(transform.eulerAngles.x,angleY,transform.eulerAngles.z);
}/// <summary>
/// 限制画布中UI的Z角度
/// </summary>
private void LimitImgAngle()
{float angleZ = transform.eulerAngles.z;if (angleZ <= 30) angleZ = 30;else if (angleZ >= 150) angleZ = 150;transform.eulerAngles = new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,angleZ);
}