[Unity3D] 随机播放攻击动画&自动寻路功能
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using UnityEngine; 5 6 public class GetRandomAnimation : MonoBehaviour 7 { 8 //定义怪物状态的枚举 9 public enum State { 10 /// <summary> 11 /// 站立 12 /// </summary> 13 Stand, 14 /// <summary> 15 /// 走路 16 /// </summary> 17 Walk, 18 /// <summary> 19 /// 攻击 20 /// </summary> 21 Attack, 22 /// <summary> 23 /// 寻路 24 /// </summary> 25 PathFinding, 26 /// <summary> 27 /// 闲置状态 28 /// </summary> 29 Idle, 30 } 31 32 //攻击动画数组(将要使用的攻击动画名称复制进去) 33 public string[] ATKAnimationList; 34 //常用动画,将动画名称一 一写入即可 35 public string Walk; 36 public string Stand; 37 public string Idle; 38 public string Die; 39 40 //声明动画组件 41 public Animator animator; 42 //默认寻路状态 43 public State CurrentState = State.PathFinding; 44 //攻击频率 45 public float AtkInterval3s = 3f; 46 //创建一个空物体并放置好位置,拖入即可生成怪物移动路线 47 public Transform[] wayPoints; 48 //当前下标 49 private int CurrentIndex; 50 //移动速度 51 public float MoveSpeed = 5f; 52 void Start() 53 { 54 //查找动画组件并赋值 55 animator = this.GetComponent<Animator>(); 56 //默认动画站立姿势 57 Playing(Stand); 58 } 59 60 61 void Update() 62 { 63 switch (CurrentState) { 64 case State.PathFinding: 65 //播放行走动画 66 Playing(Walk); 67 //如果到达了路径的终点,切换攻击状态为攻击 68 if (PathFinding() == false) { 69 CurrentState = State.Attack; 70 } 71 break; 72 case State.Stand: 73 break; 74 case State.Idle: 75 break; 76 case State.Attack: 77 //随机一个攻击动画播放 78 int animName = UnityEngine.Random.Range(0, ATKAnimationList.Length); 79 Playing(ATKAnimationList[animName]); 80 if (AtkInterval3s <= Time.time) { 81 CurrentState = State.Stand; 82 } 83 break; 84 case State.Walk: 85 break; 86 } 87 } 88 89 //播放动画 90 private void Playing(string AnimationName) { 91 animator.SetBool(AnimationName,true); 92 } 93
//自动寻路 94 public bool PathFinding() { 95 96 //如果路线值为空 或者 到达路线最大值时 返回到达目标点 97 if (wayPoints == null || CurrentIndex >= wayPoints.Length)return false; 98 99 //注视当前目标点 100 LookRotation(wayPoints[CurrentIndex].position); 101 102 //朝着目标点移动 103 MoveForward(); 104 105 //如果当前位置与目标点接近时 106 if (Vector3.Distance(this.transform.position, wayPoints[CurrentIndex].position) < 0.1f) { 107 //更换下一个坐标点 108 CurrentIndex++; 109 } 110 return true; 111 } 112 113 //注视平滑旋转 114 private void LookRotation(Vector3 Target) { 115 Quaternion dir = Quaternion.LookRotation(Target - this.transform.position); 116 this.transform.rotation = Quaternion.Lerp(this.transform.rotation, dir, 0.1f); 117 } 118 119 //移动 120 public void MoveForward() { 121 this.transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime); 122 } 123 }
自动寻路(右键新页面打开高清图)
随机切换攻击(请忽略动作位置偏移)右键新页面打开高清图
时间若流水,恍惚间逝去