C#编程逻辑(Unity3d脚本)

C# programming logic (Unity3d script)

我有一个玩家打开和关闭门的脚本,但是当我按下按钮关闭门时,它会关闭然后再次打开。我怀疑这是因为 lerp 没有停止或其他原因。我怎样才能解决这个问题?怎么了? 谢谢!

Door Script:

using UnityEngine;
using System.Collections;

public class DoorHandler : MonoBehaviour {
public bool isOpen = false;
public float maxOpenDistance = 10f, doorCloseTime = 3f;

void Update () {
    if (Input.GetKeyDown (KeyCode.F)) {
        if (Vector3.Distance (GameObject.FindGameObjectWithTag ("Player").transform.position, this.gameObject.transform.position) <= maxOpenDistance) {
            isOpen = !isOpen;
        }

    if (isOpen) 
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z),
                                                                 Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z), doorCloseTime);
        } else {
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z),
                                                               Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z), doorCloseTime);
    } 
}
}

你的花括号设置错了。您应该检查您的 IDE 是否具有自动格式化功能,以便您可以轻松找到这些错误。

void Update () {
    if (Input.GetKeyDown (KeyCode.F)) {
        if (Vector3.Distance (GameObject.FindGameObjectWithTag ("Player").transform.position, this.gameObject.transform.position) <= maxOpenDistance) {
            isOpen = !isOpen;
        }
    }

    if (isOpen) 
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z),
                                                         Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z), doorCloseTime);
    else {
        gameObject.transform.rotation = Quaternion.Lerp (Quaternion.Euler (transform.rotation.x, 90, transform.rotation.z),
                                                         Quaternion.Euler (transform.rotation.x, 0, transform.rotation.z), doorCloseTime);
    } 
}

另外我不知道你是否在检查器中为 doorCloseTime 设置了另一个值,但是 3 没有任何意义。 Lerp 在两个值之间进行线性插值。您在 Lerp 方法中指定的参考值 (t) 理想情况下应该是 0 到 1 之间的值。最后,您还应该在 Lerp 方法中设置适当的 from 值。假设您希望平滑过渡,您可能希望使用当前旋转而不是硬编码四元数。