Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(197评价)
价格: 4431.00元
[stealth秘密行动游戏开发 \ 33控制机器人行走动画的播放] 机器人无法自动寻路,而NavMsehAgent组件却开始自动寻路...
五蕴沙门发起了问答2017-12-07
6
回复
573
浏览
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设置如下

所有回复
发表回复
你还没有登录,请先 登录或 注册!