首頁>Game>source

我正在用Unity製作2D平臺遊戲.我想建立一个壓力垫以打開門,並且我希望当播放器在壓力垫上時門能打開,並在播放器离開壓力垫後几秒钟內關闭.我尝試了不同的方法,但没有一个起作用.在這種情况下,門應向上和向下關闭.另外,我已经為門建立了一些動画(空闲,打開和關闭),但是不知道如何在這两个物件之間建立連線,然後在適当的時間播放動画.預先谢谢你。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PressurePad: MonoBehaviour
{
    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;
    int objectsInContact;
    IEnumerator Timer()
    {  
        yield return new WaitForSeconds(6);
        OnDeactivate.Invoke();
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        objectsInContact++;
        if (objectsInContact == 1 && OnActivate != null) OnActivate.Invoke();
    }
    void OnTriggerExit2D(Collider2D other)
    {
        objectsInContact--;
        if (objectsInContact == 0 && OnDeactivate != null) OnDeactivate.Invoke();
        StartCoroutine(Timer());
      
    }
}
最新回復
  • 6月前
    1 #

    您非常亲近,但是 您会觸發两次停用事件:一旦垫板變空便立即觸發,然後在延迟後再次觸發。

    删除第一个,並確保在播放器在時間到之前返迴到打击垫時停止計時器:

    using System.Collections; 
    using System.Collections.Generic; 
    using UnityEngine; 
    using UnityEngine.Events; 
    public class PressurePad: MonoBehaviour {
     
        public UnityEvent OnActivate; 
        public UnityEvent OnDeactivate; 
        public float deactivationDelay = 6f;
        int objectsInContact;
        Coroutine waitingToDeactivate;
    
        IEnumerator Timer() { 
            yield return new WaitForSeconds(deactivationDelay);
            // Tell our listeners we're switched OFF.
            if (OnDeactivate != null) 
                OnDeactivate.Invoke(); 
            // Return to ready-to-activate state:
            waitingToDeactivate = null;
        } 
        void OnTriggerEnter2D(Collider2D other) { 
            objectsInContact++; 
            
            // Pressure pad pressed.
            if (objectsInContact == 1) {
                if (waitingToDeactivate != null) {
                    // Cancel deactivation timer. 
                    StopCoroutine(waitingToDeactivate);
                    waitingToDeactivate = null;
                } else if (OnActivate != null) {
                    // Tell our listeners we're switched ON.
                    OnActivate.Invoke(); 
                } 
            }
        }
        void OnTriggerExit2D(Collider2D other) { 
            objectsInContact--; 
            // Pressure pad released.
            if (objectsInContact == 0) {
                // Start a delay before telling anyone.
                waitingToDeactivate = StartCoroutine(Timer()); 
            } 
        }
    }
    

  • sprites:SNES開發:為什麼位平面会變得混亂?
  • lighting:Unity:绿線Gizmo代表什麼?