首页>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());
      
    }
}
最新回答
  • 2020-12-23
    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代表什么?