[英]I'm trying to make it so the person playing the game can press "E" as much as they want in the trigger | Unity 3d + animator
我正在开发这个我一直在制作的 Unity 3D 游戏,玩家可以点击随机按钮(不要问为什么)。 在这个游戏中,我做了一个玩家可以输入一个触发器,然后按下E来触发一次动画,同时点击它,效果非常好。 但唯一的问题是“播放器”只能使动画触发一次,而必须离开触发器并重新进入它才能使动画触发并在按下E时再次工作。
我的目标是让动画在单击时始终有效,而不是仅在触发器中每次都按住E。
这是我制作的按钮的代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fixedpress : MonoBehaviour
{
public Animator Tributton;
private Coroutine routine;
private void OnTriggerEnter(Collider other)
{
// in general rather use CompareTag instead of ==
// it is slightly faster and also shows an error if the tag doesn't exist instead of failing silent
if (!other.CompareTag("Player")) return;
// just in case to prevent concurrent routines
if (routine != null) StopCoroutine(routine);
// start a new Coroutine
routine = StartCoroutine(WaitForKeyPress());
}
private IEnumerator WaitForKeyPress()
{
// check each FRAME if the key goes down
// This is way more reliable as OnTriggerStay which is called
// in the physics loop and might skip some frames
// This also prevents from holding E while entering the trigger, it needs to go newly down
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.E));
// set the trigger once and finish the routine
// There is no way to trigger twice except exit the trigger and enter again now
Tributton.SetTrigger("Fiveyon");
Debug.Log("Fiveyon!");
// If you even want to prevent this from getting triggered ever again simply add
enabled = false;
// Now this can only be triggered ONCE for the entire lifecycle of this component
// (except you enable it from the outside again of course)
}
void OnTriggerExit(Collider other)
{
if (!other.CompareTag("Player")) return;
// when exiting the trigger stop the routine so later button press is not handled
if (routine != null) StopCoroutine(routine);
}
}
无需在 onTriggerEnter 中启动协程,只需在玩家进入触发器时将 bool 设置为 true,并使用该 bool 作为条件检索 Update 中的输入。 PS:您还可以添加一个冷却计时器,以便玩家无法在触发器内发送E。 例子:
bool canAnimate;
private void OnTriggerEnter(Collider other)
{
// in general rather use CompareTag instead of ==
// it is slightly faster and also shows an error if the tag doesn't exist instead of failing silent
if (!other.CompareTag("Player")) return;
// just in case to prevent concurrent routines
if (routine != null) StopCoroutine(routine);
canAnimate = true;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.E) && canAnimate)
{
Tributton.SetTrigger("Fiveyon");
}
}
void OnTriggerExit(Collider other)
{
if (!other.CompareTag("Player")) return;
// when exiting the trigger stop the routine so later button press is not handled
if (routine != null) StopCoroutine(routine);
canAnimate = false;
}
PS:我相信会有更好的方法来实现这一点。 让我知道它是否有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.