using UnityEngine;
using System.Collections;
public class RotateObj : MonoBehaviour
{
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float smoothTime = 2f;
float rotationYAxis = 0.0f;
float rotationXAxis = 0.0f;
float velocityX = 0.0f;
float velocityY = 0.0f;
// Use this for initialization
void Start()
{
Vector3 angles = transform.eulerAngles;
rotationYAxis = angles.y;
rotationXAxis = angles.x;
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
velocityX = 0;
velocityY = 0;
}
if (Input.GetMouseButton(0))
{
velocityX = -xSpeed * Input.GetAxis("Mouse X");
velocityY = ySpeed * Input.GetAxis("Mouse Y");
rotationYAxis += velocityX;
rotationXAxis -= velocityY;
rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
transform.rotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
return;
}
if (Input.GetMouseButtonUp(0))
{
velocityX -= xSpeed * Input.GetAxis("Mouse X") * 0.02f;
velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
}
rotationYAxis += velocityX;
rotationXAxis -= velocityY;
rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
Quaternion toRotation = Quaternion.Euler(rotationXAxis, rotationYAxis, 0);
Quaternion rotation = toRotation;
transform.rotation = rotation;
velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}
代码段-平滑的旋转一个物体
最新推荐文章于 2023-12-11 19:10:45 发布
该博客介绍了一个Unity脚本,用于平滑地旋转场景中的物体。通过调整鼠标输入,可以控制物体沿X和Y轴的平滑转动,并且限制了Y轴的转动范围。平滑效果通过速度变量和Lerp函数实现,确保旋转过程流畅。
摘要由CSDN通过智能技术生成