[英]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.