c# - 当敌人看到玩家时让他攻击
问题描述
有人可以帮我吗?我正在使用下面的代码来尝试让敌人看他是否能看到玩家。
但问题是当我在墙后他还能看到我有人能帮帮我吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
public class Test : MonoBehaviour
{
[SerializeField]
float distance;
public GameObject player;
public Transform Shootpoint;
public bool CanSee = false;
[SerializeField]
float chaseDistence = 0.5f;
void Update()
{
distance = Vector3.Distance(Shootpoint.position, player.transform.position);
if (!Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
{
Debug.DrawLine(Shootpoint.position, player.transform.position, Color.red);
CanSee = false;
Debug.Log("CANT SEE");
}
else if (Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
{
Debug.DrawLine(Shootpoint.position, player.transform.position, Color.green);
CanSee = true;
Debug.Log("CAN SEE");
}
}
}
解决方案
就像@BugFinder 提到的那样,您只是在检查是否确实与某些东西RayCast
发生了碰撞,而不一定是与玩家发生了碰撞。
如果您想确定光线是否仅与玩家碰撞,而不与其他对象发生碰撞,请使用设置RaycastHit
对象的函数重载。然后你可以得到tag
它并将它与你的播放器的标签进行比较。(参见Physics.RayCast和RaycastHit)
你可以这样实现:
RaycastHit hitInfo;
if(Physics.Raycast(Shootpoint.position, player.transform.position, out hitInfo, chaseDistence))
{
if (hitInfo.collider.CompareTag("player"))
{
// Can see
}
else
{
// Can't see, raycast hit something
}
}
else
{
// Can't see, raycast hit nothing
}
推荐阅读
- reactjs - 将接口传递给 React 类组件时出现意外标记“<”预期“{”
- scala - 无法将 MockWS 与咖啡因一起测试
- apache - 如何重置 phpMyAdmin 的 .htaccess 用户名和密码?
- python - 无法在 django 中迁移
- grafana - 更改 Grafana 表中每列的配置设置
- python - Python类继承——属性混淆
- github - GitHub Actions:将分支移动到另一个分支
- python-3.x - python中是否有一种方法可以根据列标题提取半结构化pdf表的列?
- excel - 如何使用 VBA 比较两列并突出显示差异?
- quarkus - 在 quarkus 中异步调用 @Transactional 方法