如何同时运行navmesh代理和光线投射



我正在Unity中为我的游戏AI编写代码,我想在同一代码中运行NavMesh代理,用于移动、Raycast和声音触发器(在我的游戏中,这是一个可以感知声音的敌人,如果它听到它,它会跟随它的来源(。

注意:导航网格代理。该组件连接到游戏中的移动角色,使其能够使用NavMesh

光线投射通常用于视频游戏开发中,例如作为确定玩家的视线

我试过同时运行两个单独的脚本(Raycast和NavMesh(,但都不起作用。我很抱歉,但我对用C#进行编码一无所知。

这是我写的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IAVISIBILIDAD : MonoBehaviour
{
public Transform target;
public float moveSpeed = 3;
public float rotationSpeed = 3;
public float distance = 5f;
public bool Enabled = false;
public bool Detect = false;
private Transform myTransform;

void Awake()
{
myTransform = this.GetComponent<Transform>();
}
void Start()
{
target = GameObject.FindWithTag("Player").transform;
}
void Update()
{
if (Enabled)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
RaycastHit info;
Debug.DrawRay(transform.position, transform.forward * distance, Color.red, 0.1f);
if (Physics.Raycast(transform.position, transform.forward, out info, distance))
{
if (info.collider.tag == "Player")
{
Detect = true;
}
else
{
Detect = false; 
}
}
else
{
Detect = false;
}
}
if (Enabled && Detect)
{
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Enabled = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
Enabled = false;
}
}
}

一些建议,因为您没有发布完整的代码。你绝对应该能够做到这一切

  1. 请画一条调试线,这样您就可以直观地看到您的raycast到底在做什么:https://docs.unity3d.com/ScriptReference/Debug.DrawLine.html
  2. 进行一些调试。登录您的代码以了解到底发生了什么,也就是:

示例

if (Physics.Raycast(transform.position, transform.forward, out info, distance))
{
Debug.Log("Collided with: " + info.collider.tag}");
if (info.collider.tag == "Player")
{
Detect = true;
}
else
{
Detect = false; 
}
}
else
{
Debug.Log("Failed to collide with anything");
Detect = false;
}
  1. 检查物理层https://docs.unity3d.com/Manual/LayerBasedCollision.html
  2. 仔细检查标签是否正确
  3. 仔细检查东西上是否有碰撞器

最新更新