无法弄清楚为什么门不会打开

时间:2015-10-11 10:17:15

标签: c# unity3d

嘿伙计我的代码有问题,我无法弄明白,当玩家与门碰撞或碰到它播放动画时,我正试图这样做。问题是动画根本不会播放。

另请注意,门脚本已贴在门上。

using UnityEngine;

using System.Collections;

public class DoorOpen : MonoBehaviour
{

    //this variable will decide wether door is open or not, its initially on false because the door is closed.

    bool isDoorOpen = false;

    //this variable will play the audio when the door opens
    public AudioSource sound01;

    void Start()
    {

    }
    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.name == "Bathroom_Door" && Input.GetKeyDown(KeyCode.F))
        {
            GetComponent<Animation>().Play("DoorO");
            sound01.Play();
            //this variable becomes true because the door is open
            isDoorOpen = true;
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}

1 个答案:

答案 0 :(得分:1)

如果玩家进入碰撞框,您应该检查更新中的GetKeyDown并打开门。另一个选择是使用OnCollisionStay而不是OnCollisionEnter,因为OnCollisionEnter仅在碰撞开始时被调用一次。

public class DoorOpen : MonoBehaviour
{

//this variable will decide wether door is open or not, its initially on false because the door is closed.

bool isDoorOpen = false;
bool canOpenDoor = false;

//this variable will play the audio when the door opens
public AudioSource sound01;

void Start()
{

}
void OnCollisionEnter(Collision col)
{
    if (col.gameObject.name == "Bathroom_Door")
    {
         canOpenDoor = true;
    }
}
void OnCollisionExit(Collision col)
{
    if (col.gameObject.name == "Bathroom_Door")
    {
         canOpenDoor = false;
    }
}
// Update is called once per frame
void Update()
{
     if (canOpenDoor && Input.GetKeyDown(KeyCode.F))
    {
        GetComponent<Animation>().Play("DoorO");
        sound01.Play();
        //this variable becomes true because the door is open
        isDoorOpen = true;
    }
}
}