Wolf.cs 19 KB

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