在Unity中实现点击一个物体,另一个物体在2秒内旋转90度之后再转回原位置,可以按照以下步骤进行操作:

  1. 创建一个脚本文件,比如'RotateObject.cs',并将其附加到需要旋转的物体上。

  2. 在脚本文件中,声明一个公共变量用于保存旋转的目标角度,例如:

public float targetRotation = 90f; // 目标旋转角度
public float rotationSpeed = 90f; // 旋转速度
  1. 在Update函数中,检测是否点击了物体,并在点击时开始旋转物体。可以使用Input.GetMouseButtonDown函数来检测鼠标点击事件,并使用RaycastHit来检测点击的物体。例如:
void Update()
{
    if (Input.GetMouseButtonDown(0)) // 左键点击
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.gameObject == gameObject) // 点击的是当前物体
            {
                StartCoroutine(RotateObject());
            }
        }
    }
}
  1. 创建一个协程函数来实现物体的旋转。在协程函数中,使用Quaternion.Lerp来平滑地旋转物体至目标角度。例如:
IEnumerator RotateObject()
{
    Quaternion startRotation = transform.rotation;
    Quaternion endRotation = Quaternion.Euler(0f, targetRotation, 0f);

    float t = 0f;

    while (t < 1f)
    {
        t += Time.deltaTime * rotationSpeed;
        transform.rotation = Quaternion.Lerp(startRotation, endRotation, t);
        yield return null;
    }

    yield return new WaitForSeconds(2f); // 等待2秒

    t = 0f;

    while (t < 1f)
    {
        t += Time.deltaTime * rotationSpeed;
        transform.rotation = Quaternion.Lerp(endRotation, startRotation, t);
        yield return null;
    }
}
  1. 将脚本附加到需要旋转的物体上,设置好目标旋转角度和旋转速度的数值。

现在,当你点击物体时,该物体将在2秒内旋转90度,然后再转回原来的位置。

Unity 点击物体旋转:2秒内旋转90度并返回原位

原文地址: https://www.cveoy.top/t/topic/jwgZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录