1. 程式人生 > 實用技巧 >[Unity3D] 隨機播放攻擊動畫&自動尋路功能

[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 }

自動尋路(右鍵新頁面開啟高清圖)

隨機切換攻擊(請忽略動作位置偏移)右鍵新頁面開啟高清圖