如何判断哪些对撞机发生了碰撞? [英] How to tell which of the colliders has been collided?

查看:36
本文介绍了如何判断哪些对撞机发生了碰撞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个有敌人的游戏,我想在游戏中爆头,所以我有 2 个对撞机:一个是头部,一个是身体.我找不到任何好方法来判断代码中的哪个是哪个.

I'm creating a game in which there are enemies, I want to have headshots in the game so I have 2 colliders: one to the head and one to the body. I can't find any good way to tell which is which in the code.

我想到了一个解决方案,但我不喜欢它 - 头部的碰撞器类型不同,身体的碰撞器类型不同(如多边形和盒子碰撞器).它有效,但我认为它不够好(如果我想添加更多对撞机或有两个不起作用的相同类型).

I thought of a solution but I don't like it- a different type of collider to the head, and different type to the body (like polygon and box colliders). It works but I don't think it's good enough (if I want to add more colliders or have two of the same type that wouldn't work).

virtual protected void OnTriggerEnter2D(Collider2D collider2D)
    {
        if (collider2D.gameObject.tag.Equals("Zombie"))
        {
            Destroy(gameObject);//destroy bullet
            Zombie zombie = collider2D.gameObject.GetComponent<Zombie>();
            if (collider2D is BoxCollider2D)
                zombie.HeadShot(demage);//headshot
            else zombie.BulletHit(demage);//normal hit
        }
    }

我想要一种以某种方式标记碰撞体的方法,以便我可以区分它们.

I want a way to tag the colliders somehow so I can tell between them.

推荐答案

我建议不要在同一个 GameObject 上添加所有碰撞器,而是给每个碰撞器它自己的子 GameObject(这样你也可以很容易地看到哪些碰撞体属于场景视图中的哪个轮廓;))

I would suggest to not add all colliders on the same GameObject but rather give each collider it's own child GameObject (this way you also can see easily which colliders belongs to which outline in the scene view ;) )

然后你可以使用一个带有枚举的类来定义你在那里拥有哪种类型的碰撞器:

Then you could use a class with an enum to define which type of collider you have there:

public class BodyPart : MonoBehaviour
{
    public BodyPartType Type;
}

public enum BodyPartType
{
    Head,
    LeftArm,
    RightArm,
    Body,
    LeftLeg,
    RightLeg
}

并将其附加到每个碰撞器旁边的所有身体部位.

and attach it to all body parts next to each collider.

然后你可以做类似的事情

Then you could do something like

virtual protected void OnTriggerEnter2D(Collider2D collider2D)
{
    if (collider2D.gameObject.tag.Equals("Zombie"))
    {
        Destroy(gameObject);//destroy bullet

        // Note you then should use GetComponentInParent here
        // since your colliders are now on child objects
        Zombie zombie = collider2D.gameObject.GetComponentInParent<Zombie>();

        var bodyPart = collider2D.GetComponent<BodyPart>();
        switch(bodyPart.Type)
        {
            case BodyPartType.Head:
                zombie.HeadShot(demage);//headshot
                break;

            // you now could differ between more types here

            default:
                zombie.BulletHit(demage);//normal hit
                break;
        }
    }
}

这篇关于如何判断哪些对撞机发生了碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆