Wolf.cs 18 KB

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