文章目录
前言
Uniyt版本:2022.3
实现内容:
1.点击地图,人物移动到点击位置
2.给人物添加移动动画
效果展示:
使用素材:
人物素材
导入人物素材:
Window->Package
22.3需要导入AI Navigation包
一、Navigation 智能导航地图烘焙
1.创建Plan和NavMesh Surface
2.智能导航地图烘焙
下面展示烘焙完的效果:
二、MouseManager 鼠标控制人物移动
1.给场景添加人物,并给人物添加导航组件
人物属性栏Y轴改为0.5
添加导航组件:
2.编写脚本管理鼠标控制
创建脚本:MouseManager
脚本为设计为单例模式,场景中只需要一个。
using System;
using UnityEngine;
public class MouseManager : MonoBehaviour
{
//静态对象,其他脚本可以通过这个对象来调用当前类的方法
public static MouseManager Instance;
void Awake()
{
if(Instance!=null)
{
Debug.LogError("存在多个对象,可能存在问题");
Destroy(gameObject);
}
Instance = this;
}
//事件,我认为是方法集,其他脚本可以通过这个添加一个放过进来,此脚本会在合适时机执行里面的方法
public event Action<Vector3> OnMouseClick;
RaycastHit hitInfo;//射线碰撞的对象的信息结构体
void Update()
{
MouseControl();
}
void MouseControl()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Input.GetMouseButtonDown(0)按下鼠标左击返回为true
if (Input.GetMouseButtonDown(0)&&Physics.Raycast(ray, out hitInfo))
{
Debug.Log("鼠标被点击了");
//如果点击地面就拿到点击位置给方法集
if(hitInfo.collider.gameObject.CompareTag("Ground"))
{
Debug.Log(hitInfo.point);
//?是表示如果方法集里不为空执行后面操作
OnMouseClick?.Invoke(hitInfo.point);
}
}
}
}
创建空对象命名为MouseManager挂载脚本
3.给人物编写脚本,订阅事件(添加方法给MouseManager的OnMouseClick)
using UnityEngine;
using UnityEngine.AI;
public class MouseController : MonoBehaviour
{
NavMeshAgent agent;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
}
void Start()
{
//添加方法到放过方法集里-订阅
MouseManager.Instance.OnMouseClick += MoveToTarget;
}
//告诉agent目标位置
public void MoveToTarget(Vector3 target)
{
//设置这个变量,人物就会向目标方向移动
agent.destination = target;
}
}
添加脚本给人物:
目前效果展示
三、添加人物移动动画
1.制作运动动画
运动动画有三种状态:待机,走,跑
三种状态可以通过速度来更改状态动画
- 创建Animator Controller命名为Player
双击进入动画机界面,右键空白位置,创建混合树
双击混合树,添加Float变量命名为Speed:
修改混合树参数,添加通过三种动画到混合树里
2.将动画机添加给人物
3.关联人物速度给动画
通过脚本MouseContorller将速度给动画机的Speed变量
using UnityEngine;
using UnityEngine.AI;
public class MouseController : MonoBehaviour
{
NavMeshAgent agent;
Animator anim;
void Awake()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
void Start()
{
//添加方法到放过方法集里-订阅
MouseManager.Instance.OnMouseClick += MoveToTarget;
}
void Update()
{
anim.SetFloat("Speed", agent.velocity.sqrMagnitude);
}
//告诉agent目标位置
public void MoveToTarget(Vector3 target)
{
//设置这个变量,人物就会向目标方向移动
agent.destination = target;
}
}