Wolf.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.AI;
  5. using DG.Tweening;
  6. public class Wolf : TargetAnimal
  7. {
  8. //动画播放器
  9. AnimationPlayer ap;
  10. //寻路代理
  11. NavMeshAgent agent;
  12. void Awake()
  13. {
  14. ap = GetComponent<AnimationPlayer>();
  15. agent = GetComponent<NavMeshAgent>();
  16. }
  17. void Start()
  18. {
  19. initAniListener();
  20. this.agent.avoidancePriority = avoidancePriority;
  21. }
  22. static int _avoidancePriority = 0;
  23. static int avoidancePriority {
  24. get {
  25. if (_avoidancePriority < 50) {
  26. _avoidancePriority++;
  27. } else {
  28. _avoidancePriority = 1;
  29. }
  30. return _avoidancePriority;
  31. }
  32. }
  33. void Update()
  34. {
  35. if (HasCloseToDestination()) {
  36. OnReachDestination();
  37. }
  38. UpdateAutoStrategy();
  39. UpdateAction();
  40. UpdateOutline();
  41. }
  42. //可选皮肤材质
  43. [SerializeField] Material[] materials;
  44. [SerializeField] Material[] outlineMaterials;
  45. public void ChangeColorByType(int type) {
  46. if (skinnedMeshRenderer == null) skinnedMeshRenderer = GetComponentInChildren<SkinnedMeshRenderer>();
  47. baseMaterial = materials[type - 1];
  48. outlineMaterial = outlineMaterials[type - 1];
  49. skinnedMeshRenderer.material = baseMaterial;
  50. }
  51. Material baseMaterial;
  52. Material outlineMaterial;
  53. SkinnedMeshRenderer skinnedMeshRenderer = null;
  54. bool hasOutLine = false;
  55. void UpdateOutline() {
  56. Camera camera = Camera.main;
  57. if (!camera) return;
  58. float distance = Vector3.Distance(this.transform.position, camera.transform.position);
  59. if (distance > 15) {
  60. if (!hasOutLine) {
  61. hasOutLine = true;
  62. skinnedMeshRenderer.material = outlineMaterial;
  63. }
  64. } else {
  65. if (hasOutLine) {
  66. hasOutLine = false;
  67. skinnedMeshRenderer.material = baseMaterial;
  68. }
  69. }
  70. }
  71. public override void OnHit(Arrow arrow, Vector3 hitPoint, string partName)
  72. {
  73. arrow.Head().position = hitPoint + arrow.transform.forward * 0.1f;
  74. arrow.Hit();
  75. if (partName == "Leg" || partName == "Tail") {
  76. state.hp -= 2;
  77. }
  78. else if (partName == "Body") {
  79. state.hp -= 3;
  80. }
  81. else if (partName == "Head") {
  82. state.hp -= 100;
  83. }
  84. if (state.hp > 0) {
  85. Hurt();
  86. } else {
  87. Die(arrow);
  88. }
  89. }
  90. void Die(Arrow arrow) {
  91. if (state.dead) return;
  92. arrow.onDoNextShoot += delegate() { Destroy(this.gameObject); };
  93. state.ResetActionState();
  94. state.dead = true;
  95. this.agent.enabled = false;
  96. onDie?.Invoke(this);
  97. AudioMgr.ins.PlayAnimalEffect("wolf_die", AudioMgr.GetAudioSource(this.gameObject));
  98. AudioMgr.ins.PlayCheer(true);
  99. }
  100. void Hurt() {
  101. if (!state.attacking) {
  102. if (Random.value < 0.2f) {
  103. CancelLockTarget();
  104. state.ResetActionState();
  105. state.lockingTarget = true;
  106. needAmbush = false;
  107. } else {
  108. //未锁定目标阶段是被击退,因为可能会再次满足z路径条件,因此需要重置Z路径记录
  109. if (!state.lockingTarget) ResetZPathRecord();
  110. CancelLockTarget(1);
  111. RunAwayFromHunter();
  112. }
  113. }
  114. AudioMgr.ins.PlayAnimalEffect("wolf_die", AudioMgr.GetAudioSource(this.gameObject));
  115. AudioMgr.ins.PlayCheer(true);
  116. }
  117. //启动寻路
  118. void SetDestination(Vector3 pos) {
  119. state.ResetActionState();
  120. state.moving = true;
  121. this.agent.destination = pos;
  122. }
  123. //寻路结束
  124. void OnReachDestination() {
  125. if (!state.moving) return;
  126. state.ResetActionState();
  127. }
  128. //是否已经接近目的地(寻路完成判断)
  129. bool HasCloseToDestination() {
  130. if (!state.moving) return true;
  131. if (Vector3.Distance(this.agent.nextPosition, this.agent.destination) < 0.25f) {
  132. return true;
  133. }
  134. if (state.movingTime > 0.1f && this.agent.velocity.magnitude < 0.05f) {
  135. return true;
  136. }
  137. return false;
  138. }
  139. int lastAutoType;
  140. float willStayTime;
  141. bool willAttack = false;
  142. bool hasRunAround = false;
  143. int needRunAroundCount = 0;
  144. bool hasRunToHunter = false;
  145. //取消锁定状态
  146. //cancelType==1时,表示触发逃跑
  147. void CancelLockTarget(int cancelType = 0) {
  148. if (!state.lockingTarget) return;
  149. state.lockingTarget = false;
  150. if (cancelType == 1) state.lockingTarget = true;
  151. RandomWillStayTime();
  152. willAttack = false;
  153. hasRunAround = false;
  154. if (cancelType == 1) hasRunAround = true;
  155. needRunAroundCount = 0;
  156. if (cancelType == 1) needRunAroundCount = 2;
  157. hasRunToHunter = false;
  158. if (cancelType == 1) hasRunToHunter = true;
  159. }
  160. //帧更新逻辑-自动策略
  161. void UpdateAutoStrategy() {
  162. if (state.dead) return;
  163. if (state.lockingTarget) {
  164. // if (state.attacking) {
  165. // this.transform.LookAt(this.hunterPosition);
  166. // }
  167. if (!hasRunToHunter) {
  168. hasRunToHunter = true;
  169. RunToAttackHunter(true);
  170. willAttack = true;
  171. return;
  172. }
  173. if (!state.moving && !state.attacking) {
  174. if (willAttack) {
  175. willAttack = false;
  176. Attack();
  177. needRunAroundCount = 3;
  178. return;
  179. }
  180. if (needRunAroundCount > 0) {
  181. needRunAroundCount--;
  182. RunAroundHunter(!hasRunAround);
  183. hasRunAround = true;
  184. return;
  185. }
  186. if (hasRunAround) {
  187. hasRunAround = false;
  188. RunToAttackHunter(false);
  189. }
  190. willAttack = true;
  191. return;
  192. }
  193. return;
  194. }
  195. //以下为未锁定目标时的自动策略
  196. if (state.staying) {
  197. if (state.stayingTime > willStayTime) {
  198. MoveSlowlyInZPath();
  199. }
  200. return;
  201. }
  202. if (state.moving) {
  203. lastAutoType = 2;
  204. }
  205. if (!state.staying && !state.moving) {
  206. if (lastAutoType == 1 || lastAutoType == 0) {
  207. MoveSlowlyInZPath();
  208. } else {
  209. if (!canCreateZPath && zPathPoints.Count == 0) {
  210. MoveSlowlyInZPath();//内含判断,状态将会转化为锁定目标
  211. } else {
  212. RandomWillStayTime();
  213. Stay(true);
  214. }
  215. }
  216. }
  217. }
  218. void RandomWillStayTime() {
  219. this.willStayTime = Random.value * 4 + 2;
  220. // this.willStayTime = 0;
  221. }
  222. void LookAtHunter() {
  223. this.transform.LookAt(hunterPosition);
  224. }
  225. bool needAmbush = true;
  226. //攻击
  227. void Attack() {
  228. state.ResetActionState();
  229. state.attacking = true;
  230. curAnimIndex = -1; /*注意:这样可避免狼两次使用同一攻击动作而第二次无法播放的情况 */
  231. int hurtValue = 2;
  232. if (canAttackID == "A") {
  233. int avoidancePriority = this.agent.avoidancePriority;
  234. float baseoffset = this.agent.baseOffset;
  235. Vector3 hunterPos = hunterPosition;
  236. Vector3 jumpPoint = default; //起跳点
  237. Vector3 landPoint = default; //落地点
  238. Vector3 displace = default; //位移
  239. Sequence seq = DOTween.Sequence();
  240. //伏击动作 + 转头
  241. Quaternion ambushQuaStart = transform.rotation;
  242. Vector3 rotateDir = hunterPos - transform.position; rotateDir.y = 0;
  243. Quaternion ambushQuaEnd = Quaternion.FromToRotation(Vector3.forward, rotateDir);
  244. float needRotateAngle = Quaternion.Angle(ambushQuaStart, ambushQuaEnd);
  245. this.agent.avoidancePriority = 0;
  246. if (needRotateAngle > 20) {
  247. state.ambushRotating = true;
  248. seq.Append(DOTween.To(() => 0f, value => {
  249. transform.rotation = Quaternion.Lerp(ambushQuaStart, ambushQuaEnd, value);
  250. }, 1f, needRotateAngle / 180f * 0.5f));
  251. } else {
  252. ambushQuaEnd = ambushQuaStart;
  253. }
  254. seq.AppendCallback(delegate() {
  255. state.ambushRotating = false;
  256. if (needAmbush) state.ambushing = true;
  257. });
  258. if (needAmbush) {
  259. seq.Append(DOTween.To(() => 0f, value => {
  260. this.transform.rotation = ambushQuaEnd;
  261. }, 1f, 2f));
  262. }
  263. seq.AppendCallback(delegate() {
  264. if (state.dead) {
  265. seq.Kill();
  266. return;
  267. }
  268. needAmbush = true;
  269. state.ambushing = false;
  270. state.attackA = true;
  271. #region //起点和终点计算
  272. jumpPoint = this.transform.position;
  273. hunterPos.y = jumpPoint.y;
  274. Vector3 deltaPointer = jumpPoint - hunterPos;
  275. landPoint = hunterPos + deltaPointer.normalized * 1f;
  276. displace = landPoint - jumpPoint;
  277. #endregion
  278. });
  279. //跳跃
  280. seq.Append(DOTween.To(() => 0f, value => {
  281. this.transform.position = jumpPoint + displace * value;
  282. LookAtHunter();
  283. if (value < 0.5) {
  284. this.agent.baseOffset = baseoffset + value;
  285. } else {
  286. this.agent.baseOffset = baseoffset + (1 - value);
  287. if (!state.dead && state.attackA) {
  288. state.attackA = false;
  289. playAniJumpDown();
  290. }
  291. }
  292. }, 1f, 0.8f));
  293. seq.AppendCallback(delegate() {
  294. this.agent.avoidancePriority = avoidancePriority;
  295. this.transform.position = landPoint;
  296. LookAtHunter();
  297. if (!state.dead) onAttack?.Invoke(this, hurtValue);
  298. });
  299. seq.Append(DOTween.To(() => 0f, value => {
  300. this.transform.position = landPoint;
  301. LookAtHunter();
  302. }, 1f, 0.3f));
  303. seq.AppendCallback(delegate() {
  304. if (!state.dead) stopAniJumpDown(); //停止动画,则动画自带的位移也停止变化
  305. this.transform.position = landPoint;
  306. LookAtHunter();
  307. });
  308. seq.Append(DOTween.To(() => 0f, value => {
  309. this.transform.position = landPoint;
  310. LookAtHunter();
  311. }, 1f, 0.1f)); //通过dotween是它不被动画的位移影响;
  312. seq.AppendCallback(delegate() {
  313. state.ResetActionState();
  314. });
  315. } else if (canAttackID == "B") {
  316. state.attackB = true;
  317. hurtValue = 3;
  318. onAttack?.Invoke(this, hurtValue);
  319. }
  320. }
  321. //逃跑远离猎人
  322. void RunAwayFromHunter()
  323. {
  324. Vector3 backVec = GetPointerHunterToMe();
  325. SetDestination(transform.position + backVec.normalized * 6);
  326. state.moveQuickly = true;
  327. this.agent.speed = 5f;
  328. }
  329. //跑到能攻击玩家的坐标点
  330. string canAttackID = null;
  331. void RunToAttackHunter(bool quickly) {
  332. float needDistance;
  333. Vector3 displace = GetPointerHunterToMe().normalized;
  334. // if (Random.value < 0.33f) {
  335. // needDistance = 2;
  336. // canAttackID = "B";
  337. // } else {
  338. needDistance = 8.5f;
  339. canAttackID = "A";
  340. // }
  341. Vector3 newPos = animalsBaseT.position + displace * needDistance;
  342. SetDestination(newPos);
  343. state.moveSlowly = !quickly;
  344. state.moveQuickly = quickly;
  345. agent.speed = quickly ? 5f : 0.8f;
  346. }
  347. //在敌人身边奔跑徘徊
  348. void RunAroundHunter(bool quickly) {
  349. float baseDistance = 10;
  350. float baseDistanceMoveRange = 10;
  351. Vector3 standardPointer = animalsBaseT.forward;
  352. Vector3 pointerWithLen = standardPointer.normalized * (baseDistance + Random.value * baseDistanceMoveRange);
  353. pointerWithLen = Quaternion.AngleAxis(-40f + Random.value * 80f, Vector3.up) * pointerWithLen;
  354. Vector3 newPos = animalsBaseT.position + pointerWithLen;
  355. SetDestination(newPos);
  356. state.moveSlowly = !quickly;
  357. state.moveQuickly = quickly;
  358. agent.speed = quickly ? 5f : 0.8f;
  359. }
  360. //Z字型路径缓慢移动
  361. Queue<Vector3> zPathPoints = new Queue<Vector3>();
  362. bool canCreateZPath = true;
  363. void ResetZPathRecord() {
  364. zPathPoints.Clear();
  365. canCreateZPath = true;
  366. }
  367. void MoveSlowlyInZPath() {
  368. if (zPathPoints.Count > 0) {
  369. SetDestination(zPathPoints.Dequeue());
  370. state.moveSlowly = true;
  371. agent.speed = 0.8f;
  372. return;
  373. }
  374. if (!canCreateZPath) {
  375. state.lockingTarget = true;
  376. return;
  377. }
  378. //构建Z字型路径
  379. zPathPoints.Clear();
  380. Vector3 standardPos = animalsBaseT.forward;
  381. Vector3 hunterPos = hunterPosition;
  382. Vector3 pointerToMe = GetPointerHunterToMe().normalized;
  383. Vector3 pointer1 = Quaternion.AngleAxis(120, Vector3.up) * pointerToMe;
  384. Vector3 pointer2 = Quaternion.AngleAxis(-120, Vector3.up) * pointerToMe;
  385. Vector3 myPos = this.transform.position;
  386. int[] pointerSeq = {1, 2, 1};
  387. bool isReverse = Random.value < 0.5;
  388. foreach (int seqID in pointerSeq)
  389. {
  390. Vector3 lastMyPos = myPos;
  391. if (seqID == 1) myPos = myPos + (isReverse ? pointer2 : pointer1) * 5;
  392. if (seqID == 2) myPos = myPos + (isReverse ? pointer1 : pointer2) * 10;
  393. hunterPos.y = myPos.y;
  394. Vector3 hunterToMe = myPos - hunterPos;
  395. float angle = Vector3.Angle(hunterToMe, standardPos);
  396. float minDistance = 10;
  397. //如果下一个构建的坐标在猎手身后或者距离猎手低于指定距离
  398. if (angle > 90 || Vector3.Distance(hunterPos, myPos) < minDistance) {
  399. Vector3 hunterToMe2 = lastMyPos - hunterPos;
  400. if (hunterToMe2.magnitude > minDistance + 2) {
  401. Vector3 displace = (hunterToMe2).normalized * minDistance;
  402. myPos = hunterPos + displace;
  403. zPathPoints.Enqueue(myPos);
  404. }
  405. canCreateZPath = false;
  406. break;
  407. } else {
  408. zPathPoints.Enqueue(myPos);
  409. }
  410. }
  411. }
  412. //停留
  413. void Stay(bool correct = false) {
  414. if (state.moving || correct) {
  415. this.agent.destination = this.agent.nextPosition;
  416. }
  417. state.ResetActionState();
  418. state.staying = true;
  419. }
  420. //动画播放
  421. int curAnimIndex = 0;
  422. void playAniStay() {
  423. ap.play(curAnimIndex = 7, WrapMode.Loop);
  424. }
  425. bool isAniStay() {
  426. return curAnimIndex == 7;
  427. }
  428. void playAniMoveSlowly() {
  429. ap.play(curAnimIndex = 5, WrapMode.Loop);
  430. }
  431. bool isAniMoveSlowly() {
  432. return curAnimIndex == 5;
  433. }
  434. void playAniMoveQuickly() {
  435. ap.play(curAnimIndex = 4, WrapMode.Loop);
  436. }
  437. bool isAniMoveQuickly() {
  438. return curAnimIndex == 4;
  439. }
  440. void playAniAmbush() {
  441. ap.play(curAnimIndex = 3, WrapMode.Loop);
  442. }
  443. bool isAniAmbush() {
  444. return curAnimIndex == 3;
  445. }
  446. void playAniAttakA() {
  447. ap.play(curAnimIndex = 1, WrapMode.Once);
  448. }
  449. bool isAniAttakA() {
  450. return curAnimIndex == 1;
  451. }
  452. void playAniJumpDown() {
  453. ap.play(curAnimIndex = 6, WrapMode.Once);
  454. }
  455. void stopAniJumpDown() {
  456. ap.StopAnimation(6);
  457. }
  458. void playAniAttakB() {
  459. ap.play(curAnimIndex = 0, WrapMode.Once);
  460. }
  461. bool isAniAttakB() {
  462. return curAnimIndex == 0;
  463. }
  464. void playAniDie() {
  465. ap.play(curAnimIndex = 2, WrapMode.Once);
  466. }
  467. bool isAniDie() {
  468. return curAnimIndex == 2;
  469. }
  470. void initAniListener() {
  471. this.ap.completeCallback = delegate(AnimationPlayerCompleteResult res) {
  472. if (res.index == 0) {
  473. this.state.ResetActionState();
  474. }
  475. };
  476. }
  477. //帧更新逻辑-通过状态更新动作动画
  478. void UpdateAction() {
  479. if (state.staying) {
  480. state.stayingTime += Time.deltaTime;
  481. if (!isAniStay()) playAniStay();
  482. }
  483. else if (state.moving) {
  484. state.movingTime += Time.deltaTime;
  485. if (state.moveSlowly && !isAniMoveSlowly()) playAniMoveSlowly();
  486. if (state.moveQuickly && !isAniMoveQuickly()) playAniMoveQuickly();
  487. }
  488. else if (state.attacking) {
  489. if (state.ambushRotating && !isAniMoveQuickly()) playAniMoveQuickly();
  490. if (state.ambushing && !isAniAmbush()) playAniAmbush();
  491. if (state.attackA && !isAniAttakA()) playAniAttakA();
  492. if (state.attackB && !isAniAttakB()) playAniAttakB();
  493. }
  494. else if (state.dead) {
  495. if (!isAniDie()) playAniDie();
  496. }
  497. }
  498. //状态
  499. [System.Serializable]
  500. public class State {
  501. //数值区
  502. public int hp = 1;
  503. //动作区
  504. public bool staying = false;
  505. public bool moving = false;
  506. public bool moveSlowly = false; //慢走
  507. public bool moveQuickly = false; //跑动
  508. public bool attacking = false;
  509. public bool ambushRotating = false; //扑击前的转身
  510. public bool ambushing = false; //扑击前的伏击状态
  511. public bool attackA = false; //扑击
  512. public bool attackB = false; //撕咬
  513. public bool dead = false;
  514. public float stayingTime = 0;
  515. public float movingTime = 0;
  516. //特定区
  517. public bool lockingTarget = false; //锁定目标,只有锁定目标后,才能调用攻击接口,这是给自己的规定
  518. //重置动作区状态
  519. public void ResetActionState() {
  520. this.staying = false;
  521. this.moving = false;
  522. this.moveSlowly = false;
  523. this.moveQuickly = false;
  524. this.attacking = false;
  525. this.ambushRotating = false;
  526. this.ambushing = false;
  527. this.attackA = false;
  528. this.attackB = false;
  529. this.dead = false;
  530. this.stayingTime = 0;
  531. this.movingTime = 0;
  532. }
  533. }
  534. [SerializeField] public State state = new State();
  535. //委托
  536. public System.Action<Wolf> onDie;
  537. public System.Action<Wolf, int> onAttack;
  538. }