我一直在尝试设置一个敌人在巡逻路线上,而不是追逐我的玩家角色。我想使用光线投射,这样敌人就可以发现玩家并开始追逐玩家。它的功能正如我所想的那样。然而,即使当我们之间有障碍物或墙壁,或者当我从后面接近时,敌人“看到”我的玩家并开始追逐我。它似乎忽略了光线投射。而是集中在接近敌人的地方。
Enemy spotting player through wall
public class EnemyController : MonoBehaviour
{
private NavMeshAgent enemy;// assaign navmesh agent
private Transform playerTarget;// reference to player's position
private float attackRadius = 10.0f; // radius where enemy will spot player
public Transform[] destinationPoints;// array of points for enemy to patrol
private int currentDestination;// reference to current position
public bool canSeePlayer = false;
private Ray enemyEyes;
public RaycastHit hitData;
private void Awake()
{
enemy = GetComponent<NavMeshAgent>();
playerTarget = GameObject.Find("Player").GetComponent<Transform>();
enemyEyes = new Ray(transform.position, transform.forward);
}
private void Start()
{
Physics.Raycast(enemyEyes, attackRadius);
}
private void Update()
{
Lurk();
Debug.DrawRay(transform.position, transform.forward * attackRadius);
}
void Lurk()
{
Debug.Log("Lurking");
float distanceToPlayer = Vector3.Distance(transform.position, playerTarget.position);
//check if raycast hits playerLayer and enemy is close enough to attack
if (Physics.Raycast(enemyEyes, out hitData, attackRadius * 2, layerMask: ~6) && distanceToPlayer < attackRadius)
{
Debug.Log("You hit " + hitData.collider.gameObject.name);
ChasePlayer();
}
else
{
canSeePlayer = false;
Patrol();
}
}
void Patrol()
{
if (!canSeePlayer && enemy.remainingDistance < 0.5f)
{
enemy.destination = destinationPoints[currentDestination].position;
UpdateCurrentPoint();
}
}
void UpdateCurrentPoint()
{
if (currentDestination == destinationPoints.Length - 1)
{
currentDestination = 0;
}
else
{
currentDestination++;
}
}
void ChasePlayer()
{
StartCoroutine(ChaseTime());
canSeePlayer = true;
transform.LookAt(playerTarget.position);
Vector3 moveTo = Vector3.MoveTowards(transform.position, playerTarget.position, attackRadius);
enemy.SetDestination(moveTo);
}
IEnumerator ChaseTime()
{
Debug.Log("Chasing");
yield return new WaitForSeconds(10.0f);
if (!Physics.Raycast(enemyEyes, out hitData, attackRadius * 2, layerMask: ~6))
{
canSeePlayer = false;
Debug.Log("Lurking");
Lurk();
}
}
}
我删除了图层遮罩的波浪号“~,”但这样敌人就看不到玩家了。我初始化并设置了一个图层遮罩引用“playerLayer,”并用它代替了“layermask:~6”,无效。我使用int引用Player图层,无效。我使用按位运算符引用Player图层,无效。我删除了distanceToPlayer条件,但敌人看不到玩家。我调整了射线的长度,但如果它比攻击半径短,它就不起作用。
1条答案
按热度按时间bfrts1fy1#
关于通过墙检测玩家,我会尝试在Lurk方法中添加一个额外的if语句。这个条件将检查光线投射是否接触到墙,如果是,就不要继续这个方法,如果不是,继续。很抱歉以这种形式给出代码,但我没有访问计算机的权限,手机也不想合作
enter image description here