unity3d - 如何创建允许炮塔查看玩家是否在墙后的 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).
}
}
解决方案
您需要做的就是从炮塔投射到玩家身上并检测光线投射击中了什么。您当前的代码将蒙版设置为仅在播放器上,因此它永远不会撞墙。您可以将代码更改为以下内容:
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
}
}
}
推荐阅读
- openwhisk - openwhisk 中的 idle_container 配置
- javascript - Javascript Json 格式化
- asp.net - Docker Nginx 代理 - Angular App 中 POST 请求的 CORS 错误
- reactjs - React - 如何在按钮 onClick 中使用钩子
- reactjs - 在工厂组件渲染的组件中调用函数
- gnome - 通过 gsettings 对 Gedit 的更改似乎被忽略了
- r - R中的“堆叠”(集成)模型 - 零训练错误?
- c# - 如何在 MORYX 模块中注册 WFC 主机工厂?
- python - Django dumpdata 在特殊字符上失败
- python - 如何在带有 Python 3.8 的 Spyder 中使用 FEniCS?