Wolf.cs 20 KB

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