首页 > 解决方案 > 如何创建允许炮塔查看玩家是否在墙后的 Raycast?

问题描述

所以,基本上,我创建了一个非常简单的炮塔脚本,只要玩家在一定的范围内,基本上就可以顺利瞄准玩家。我遇到的问题是,我编写的 Raycast 实际上会检查“子弹”(这没什么——它只是一个光线投射)是否会击中目标。这意味着即使玩家躲在墙后,炮塔仍然可以射击他。我当前的光线投射脚本允许光线投射直接穿过墙壁,由于我是 Unity 新手,我不知道如何让它检查它击中的第一个对象是否是玩家,这样它就不能穿过墙壁。这是我当前的光线投射脚本:

void Shoot()
{

    //I think the problem is here - I want the raycast to return false if it hits a wall - which has the layer "ground", and true if it hits the player. Problem is, I need to make the turret return to resting position when the player is behind a wall.
    //To do this, I can just set inRange = true; But I need to be able to determine when the player is behind a wall.

    LayerMask layerMask = LayerMask.GetMask("Player");

    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hit, Mathf.Infinity, layerMask))

    {
        //This determines how much damage will the player take.
        int damage = Random.Range(1, 5);

        hit.collider.gameObject.GetComponent<playerMovement>().Shot(damage);

        //I personally THINK this means that it only triggers collisions with the player, which is why it is not working. 
        // The player has layer "Player", and tag "Player", so if anyone who wants to help can figure out how to make it stop when it hits anything - and then only return true if it hit the player (meaning the player is not behind walls).
    }


}

标签: unity3dcollision

解决方案


您需要做的就是从炮塔投射到玩家身上并检测光线投射击中了什么。您当前的代码将蒙版设置为仅在播放器上,因此它永远不会撞墙。您可以将代码更改为以下内容:

private LayerMask layerMask = (1 << LayerMask.NameToLayer("Player") | (1 << LayerMask.NameToLayer("ground")));

void Update () {
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hit, Mathf.Infinity, layerMask))
    {
        if(hit.collider.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            // you can shoot as you see the player   
        }
        else
        {
            // you hit the ground - player is behind a wall   
        }
    }
}   

推荐阅读