Wolf.cs 19 KB

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