弄不明白为什么门打不开
本文关键字:为什么 明白 | 更新日期: 2023-09-27 18:17:12
嘿,伙计们,我的代码有一个问题,我不能弄清楚,我试图使它,所以当玩家与门碰撞或触摸它,它播放动画。问题是动画根本不播放。
还要记住,门脚本是附在门上的。
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()
{
}
}
你应该检查更新中的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;
}
}
}