我在尝试创造一个游荡的人工智能。我使用统一标准资产第三方人工智能,但问题是AI只是移动到某个点,它不能在这些点之间巡逻
下面是代码:
using System;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (UnityEngine.AI.NavMeshAgent))]
[RequireComponent(typeof (ThirdPersonCharacter))]
public class AICharacterControl : MonoBehaviour
{
// the navmesh agent required for the path finding
public UnityEngine.AI.NavMeshAgent agent { get; private set; }
// the character we are controlling
public ThirdPersonCharacter character { get; private set; }
// target to aim for
public Transform target;
private void Start()
{
// get the components on the object we need (should not be null
// due to require component so no need to check)
agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
character = GetComponent<ThirdPersonCharacter>();
agent.updateRotation = false;
agent.updatePosition = true;
}
private void Update()
{
if (target != null)
agent.SetDestination(target.position);
if (agent.remainingDistance > agent.stoppingDistance)
character.Move(agent.desiredVelocity, false, false);
else
character.Move(Vector3.zero, false, false);
}
public void SetTarget(Transform target)
{
this.target = target;
}
}
}我怎样才能修改它来巡逻?
发布于 2017-04-21 05:46:25
要在两个点之间进行AI巡逻,您需要定义第二个点,并改变AI的行为,以便在到达第一个点时改变目标。目前,一旦它到达目标(即停止),它将以零速度移动。
在不过多修改代码的情况下,您可以通过这样的操作将代码扩展到两个位置之间。
using System;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (UnityEngine.AI.NavMeshAgent))]
[RequireComponent(typeof (ThirdPersonCharacter))]
public class AICharacterControl : MonoBehaviour
{
// the navmesh agent required for the path finding
public UnityEngine.AI.NavMeshAgent agent { get; private set; }
// the character we are controlling
public ThirdPersonCharacter character { get; private set; }
public Transform start;
public Transform end;
private Transform target;
private boolean forward = true;
private void Start()
{
// get the components on the object we need ( should not be null
// due to require component so no need to check )
agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
character = GetComponent<ThirdPersonCharacter>();
agent.updateRotation = false;
agent.updatePosition = true;
}
private void Update()
{
if (target != null)
agent.SetDestination(target.position);
if (agent.remainingDistance > agent.stoppingDistance)
{
character.Move(agent.desiredVelocity, false, false);
}
else
{
SetTarget(forward ? start : end);
forward = !forward;
}
}
public void SetTarget(Transform target)
{
this.target = target;
}
}
}正如您所看到的,我已经修改了Update(),让AI在离当前目标太近的情况下改变目标。还有一个额外的转换定义(start)在顶部需要设置,和一个boolean用来存储哪个方向的人工智能正在进行。
这段代码还没有在Unity中进行测试,因此可能需要进行一些修改,但它应该会给您正确的想法。
https://stackoverflow.com/questions/43534466
复制相似问题