Wolf.cs 19 KB

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