简体   繁体   中英

Unity 2D C# hitbox with boxcollider

I have some game objects on screen and added a polygon collider on them to detect normal collision with them. I would like to add a box collider on their head to detect headshot. How can i do this please? How can i state collision with box collider instead of polygon collider in C# please?

i tried this but only the polygon collider is getting detected

void OnCollisionEnter2D(Collision2D col) {
    if(col.gameObject.tag == "target")
    {
        score += 1000;
        gameObject.SetActive (false);
        gameObject.SetActive (true);
        Destroy (col.gameObject);
    }
    else if(col is BoxCollider2D)
    {
        score += 2000;
        gameObject.SetActive (false);
        gameObject.SetActive (true);
        Destroy (col.gameObject);
    }
}

Just add one more BoxCollider2D Component on the item and position it on the head. Remember to keep these in mind: https://docs.unity3d.com/Manual/CollidersOverview.html

You can easily check what type of collider was hit by just adding this in your Collision event :

void OnCollisionEnter(Collision col)
{
    if (col is BoxCollider2D)
    {
        //When it hits the box
    }
    else if(col is PolygonCollider2D)
    {
        //When it hits the polygon
    }

}

In this case it will check if the collider is a BoxCollider2D or a PolygonCollider2D and in each if statement you can do what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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