using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAnimation : MonoBehaviour
{
private NavMeshAgent navAgent;
private Animator anim;
void Awaker()
{
navAgent = this.GetComponent<NavMeshAgent>();
anim = this.GetComponent<Animator>();
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (navAgent.desiredVelocity == Vector3.zero)
{
anim.SetFloat("Speed", 0);
anim.SetFloat("AngularSpeed", 0);
}
else
{
float angle = Vector3.Angle(transform.forward, navAgent.desiredVelocity);
float angleRad = 0f;
if (angle > 90)
{
anim.SetFloat("Speed", 0);
}
else
{
Vector3 projection = Vector3.Project(navAgent.desiredVelocity, transform.forward);
anim.SetFloat("Speed", projection.magnitude);
angleRad = angle * Mathf.Deg2Rad;
Vector3 crossRes = Vector3.Cross(transform.forward, navAgent.desiredVelocity);
if (crossRes.y < 0)
{
angleRad = -angleRad;
}
anim.SetFloat("AngularSpeed", angleRad);
}
}
}
}
EnemyAnimation组件已经启用并且挂载在enemy上,32节的EnemyMove寻路也已经挂载,但是enemy无法自动巡逻,游戏开始后观察发现enemy的NavMsehAgent组件开始巡逻,而游戏模型并没有反应。
EnemyMove的代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyMove : MonoBehaviour
{
public Transform[] wayPoints;
public float patrolTime = 3f;
private float patrolTimer = 2;
private int index = 0;
private NavMeshAgent navAgent;
void Awake()
{
navAgent = this.GetComponent<NavMeshAgent>();
navAgent.destination = wayPoints[index].position;
navAgent.updatePosition = false;
navAgent.updateRotation = false;
}
void Update () {
Patrolling();
}
private void Patrolling()
{
if (navAgent.remainingDistance < 0.5f)
{
patrolTimer += Time.deltaTime;
if (patrolTimer > patrolTime)
{
index++;
index %= 4;
navAgent.destination = wayPoints[index].position;
navAgent.updatePosition = false;
navAgent.updateRotation = false;
patrolTimer = 0;
}
}
}
}
U3D设置如下