Wolf.cs 20 KB

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