简体   繁体   English

使用 OnTriggerEnter2D 检测我的游戏对象上的某些对撞机

[英]Detecting certain colliders on my game object with OnTriggerEnter2D

So, I have an enemy game object with 2 triggers attached to it.所以,我有一个敌人的游戏对象,上面有 2 个触发器。 What I want to achieve is that the enemy will do a separate attack depending on which trigger the player has collided with.我想要实现的是,敌人将根据玩家碰撞的触发器进行单独的攻击。 So there is a left trigger and a right trigger and these triggers have been saved into a public array on the enemy game object.所以有一个左触发器和一个右触发器,这些触发器已保存到敌人游戏对象上的公共数组中。 Here is the code that I thought would achieve the goal however, the if else statement always returns false when it should be returning true.这是我认为可以实现目标的代码,但是 if else 语句在应该返回 true 时总是返回 false。

private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "ThePlayer")
        {
            if (collision == DamageTriggers[0])
            {
                LeftClawAttack();
            }
            else if (collision == DamageTriggers[1])
            {
                RightClawAttack();
            }
            else
            {
                Debug.Log("False");
            }
        }
    }

If anyone can show me what I am doing wrong here and help me to find a solution to this problem it will be greatly appreciated.如果有人能告诉我我在这里做错了什么并帮助我找到解决这个问题的方法,我将不胜感激。

Thanks to Jadon Wolfgang I have been able to figure out why my code wasn't working.感谢 Jadon Wolfgang 我已经能够弄清楚为什么我的代码不起作用。 So the problem was that I was comparing Box Colliders and not collisions, so to fix this problem I found that you can use a function called IsTouching()所以问题是我比较的是 Box Colliders 而不是碰撞,所以为了解决这个问题,我发现你可以使用一个名为IsTouching()的函数

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "ThePlayer")
        {
            if (DamageTriggers[0].IsTouching(collision))
            {
                LeftClawAttack();
            }
            else if (DamageTriggers[1].IsTouching(collision))
            {
                RightClawAttack();
            }
            else
            {
                Debug.Log("False");
            }
        }
    }

Here is the new code if anyone else was having a similar problem.如果其他人遇到类似问题,这里是新代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM