忽略父对象之间的碰撞以检测其子游戏对象之间的碰撞

问题描述 投票:0回答:1

Player is my game object which moves around 2d map and tries to hit goblin with his weapon, but if weapons of goblin and player collide i dont want damage to be delt

  • 如果武器与身体碰撞会造成伤害,如果武器与其他武器碰撞则不会造成伤害。

  • 问题是,当两个武器碰撞时,它会检测到玩家对象和哥布林对象碰撞,而不是实际的武器碰撞。

  • 我已经尝试过:

    • 添加和删除刚体。
    • 从玩家游戏对象中提取子项,因为不知何故武器碰撞盒成为玩家的一部分,并且我无法获得武器与武器的碰撞。

visualization of collisions2D

 public class ObjectDamage : MonoBehaviour
{
    public int damage;
    public int team;
    public float bounceForce = 5f;

    void Start()
    {
        
    }

    void Update()
    {
        
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {   
        Debug.Log($"Collided with object with tag: {collision.gameObject.tag}"); 
        if (collision.gameObject.layer == 3)
        {
            ClashWithOtherWeapon();
            Debug.Log("Reached!");
            return;
        }

        ObjectHealth objectHealth = collision.gameObject.GetComponent<ObjectHealth>();
        if (objectHealth != null && objectHealth.team != team)
        {
            objectHealth.TakeDamage(damage);
            BounceEnemyBack(collision);
        }
    }

    private void ClashWithOtherWeapon()
    {
        return;
    }

    private void BounceEnemyBack(Collision2D collision)
    {
        Rigidbody2D rb = collision.gameObject.GetComponent<Rigidbody2D>();
        if (rb != null)
        {
            Vector2 bounceDirection = collision.transform.position - transform.position;
            bounceDirection.Normalize();
            rb.AddForce(bounceDirection * bounceForce, ForceMode2D.Impulse);
        }
    }
}
c# unity-game-engine collision-detection collision
1个回答
0
投票

您应该检查

collision.collider
,它代表与当前对象碰撞的
Collider
组件。
collision.gameObject
指的是与碰撞器关联的
Rigidbody
所附着的游戏对象。

© www.soinside.com 2019 - 2024. All rights reserved.