Animals.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /** 动物挂载脚本 */
  2. import { AnimalState } from "../../game/data/GameData";
  3. const { ccclass, property } = cc._decorator;
  4. @ccclass
  5. export default class Animals extends cc.Component {
  6. @property(cc.Animation)
  7. ani: cc.Animation = null;
  8. clipArr: Array<cc.AnimationClip> = new Array<cc.AnimationClip>();
  9. private _state: AnimalState = -1;
  10. configID = 0;
  11. curTargetPoint: cc.Vec2 = null;
  12. angle = null;
  13. speed = 0.5;
  14. walkTotleFarme = 0;
  15. isWalk = false;
  16. pointIndex = -1;
  17. pastureData = null;
  18. start() {
  19. this.curTargetPoint = this.node.getPosition();
  20. this.getNextPoint();
  21. }
  22. setState(state, configID) {
  23. this.configID = configID;
  24. if (!this.pastureData) {
  25. this.pastureData = gData.pastureSystem.getPastureData(configID);
  26. }
  27. if (this._state == state) {
  28. return;
  29. }
  30. this._state = state;
  31. let clipName = ''
  32. switch (this._state) {
  33. case AnimalState.Hanger:
  34. clipName = this.configID + '_' + 0;
  35. break;
  36. case AnimalState.Eat:
  37. clipName = this.configID + '_' + 1;
  38. break;
  39. case AnimalState.Wait:
  40. clipName = this.configID + '_' + 2;
  41. break;
  42. }
  43. this.ani.play(clipName);
  44. }
  45. getNextPoint() {
  46. let ran = Math.random() * 2 + 3;
  47. this.scheduleOnce(() => {
  48. this.pointIndex = this.pastureData.getCanMoveIndex(this.pointIndex);
  49. this.curTargetPoint = this.pastureData.getCanMoveIndexPoint(this.pointIndex);
  50. let distance = this.node.getPosition().sub(this.curTargetPoint).mag();
  51. this.angle = Math.atan2(this.curTargetPoint.y - this.node.position.y, this.curTargetPoint.x - this.node.position.x);
  52. this.walkTotleFarme = distance / this.speed;
  53. let clipName = this.configID + '_' + 1;
  54. this.node.angle = this.angle;
  55. if (this.curTargetPoint.x > this.node.position.x) {
  56. this.node.scaleX = -0.3;
  57. }
  58. else {
  59. this.node.scaleX = 0.3;
  60. }
  61. this.ani.play(clipName);
  62. this.isWalk = true;
  63. }, ran)
  64. }
  65. update(dt) {
  66. if (this.isWalk) {
  67. let x = Math.cos(this.angle) * this.speed;
  68. let y = Math.sin(this.angle) * this.speed;
  69. this.node.setPosition(this.node.getPosition().add(cc.v2(x, y)));
  70. this.walkTotleFarme--;
  71. if (this.walkTotleFarme <= 0) {
  72. this.isWalk = false;
  73. this.node.setPosition(this.curTargetPoint);
  74. this.setState(this._state, this.configID);
  75. this.getNextPoint();
  76. }
  77. }
  78. }
  79. }