Wolf.cs 19 KB

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