【问题标题】:Which collider should i use and why to use it?我应该使用哪个对撞机以及为什么要使用它?
【发布时间】:2020-10-17 00:33:58
【问题描述】:

我的想法基本上是当我得分时我得到 2 分,但是当我触摸某个变为 3 的对撞机时,我很难弄清楚要使用什么对撞机以及如何使用它们。

我想我需要使用另一个 ontriggerenter

当我触摸立方体时,它应该变为 3

if (i touch a certain collider)
{
    void OnTriggerEnter(Collider other)
    {
        ScoringSystem.theScore += 3;
    }
}
else 
{
    ScoringSystem.theScore += 2;
}

【问题讨论】:

    标签: unity3d scripting


    【解决方案1】:

    首先,我们需要创建一个 GameManager 来处理检查我们当前是否在线的 Bool。我们这样做是为了从所有脚本中访问它。

    此代码应位于 GameManager 对象中。

    // Variable to check if the player is on the line or not
    public bool stayingOnLine = false;
    
    #region Singelton
    public static GameManager instance;
    
    void Awake()
    {
        if (instance != null) {
            Debug.LogWarning("More than one Instance of GameManager found");
            return;
        }
    
        instance = this;
    }
    #endregion
    

    然后我们将此代码添加到处理 LineCollider 的 GameObject 中,以处理玩家何时进入 Line 以及何时离开。发生这种情况时,我们会从 GameManager 更改变量。

    此代码应位于设置为 IsTrigger 的 LineCollider 所在的 GameObject 中。

    GameManager gm;
    
    void Start() {
            gm = GameManager.instance;
    }
        
    void OnTriggerEnter(Collider col) {
        // Player has entered the Line ColliderBox
        if (col.CompareTag("Player Tag"))
            gm.stayingOnLine = true;
    }
    
    void OnTriggerExit(Collider col) {
        // Player has left the Line ColliderBox
        if (col.CompareTag("Player Tag"))
            gm.stayingOnLine = false;
    }
    

    之后,我们还需要向管理 HoopCollider 的 GameObject 添加代码。因为当Ball进入时,我们需要检查stayOnline是真还是假,然后给出不同的分数。

    GameManager gm;
    
    void Start() {
            gm = GameManager.instance;
    }
        
    void OnTriggerEnter(Collider col) {
        // Ball has entered the Hoop ColliderBox
        if (!col.CompareTag("Ball Tag"))
            return;
        
        if (gm.stayingOnLine)
           ScoringSystem.theScore += 3;
        else
           ScoringSystem.theScore += 2;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2018-11-12
    • 2014-06-01
    • 1970-01-01
    • 2014-03-29
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多