Wolf.cs 20 KB

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