Wolf.cs 18 KB

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