简体   繁体   English

Unity Raycasthit无法识别带标记的对象

[英]Unity Raycasthit doesn't recognized object with tag

I have an object in my game that is tagged as "Enemy" and it's in a layer called "Enemy" as well. 我的游戏中有一个标记为“Enemy”的对象,它也位于一个名为“Enemy”的层中。 It has a BoxCollider and a Rigidbody attached to it. 它有一个BoxCollider和一个Rigidbody The option IsTrigger is activated. 选项IsTrigger已激活。 When I shoot at it the hit is not recognized. 当我向它射击时,击中不被识别。 The hit passes right through it. 命中通过它。

I use this method to shoot: 我用这种方法拍摄:

void DisparaBala()
{
    RaycastHit hit;
    if(Physics.Raycast(maiCam.transform.position, maiCam.transform.forward, out hit))
    {
        print("We hit: " + hit.transform.gameObject.tag);
        if (hit.transform.tag == Tags.ENEMY_TAG)
        {
            hit.transform.GetComponent<ScriptVida>().DanoAplicado(damage);
        }
    }
}

The gun is child of a camera which is child of the player. 枪是玩家的孩子的相机的孩子。 The player is in a layer called "Player". 玩家位于一个名为“玩家”的层中。

The funny thing is if I put any other object with the tag "Enemy" the hit is recognized normally. 有趣的是,如果我将任何其他对象与标签“Enemy”放在一起,则可以正常识别命中。

I don't know what to do. 我不知道该怎么办。

Screenshot 截图

Add a layer mask to your Physics.Raycast. 在Physics.Raycast中添加图层蒙版。 Like so: 像这样:

void DisparaBala()
{
    RaycastHit hit;
    int layerMask = LayerMask.GetMask("Enemy");
    if(Physics.Raycast(maiCam.transform.position, maiCam.transform.forward, out hit, layerMask))
    {
        print("We hit: " + hit.transform.gameObject.tag);
        if (hit.transform.tag == Tags.ENEMY_TAG)
        {
            hit.transform.GetComponent<ScriptVida>().DanoAplicado(damage);
        }
    }
}

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

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