moveDest.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { GameLogic } from "./GameLogic";
  2. const {ccclass, property} = cc._decorator;
  3. @ccclass
  4. export default class MoveDest extends GameLogic {
  5. private _speed: number = 100;
  6. public get speed(): number {
  7. return this._speed;
  8. }
  9. public set speed(value: number) {
  10. this._speed = value;
  11. }
  12. private _destination: cc.Vec2 = cc.v2(0, 0);
  13. public get destination(): cc.Vec2 {
  14. return this._destination;
  15. }
  16. public set destination(value: cc.Vec2) {
  17. this._destination = value;
  18. }
  19. x_max: number;
  20. y_max: number;
  21. protected onLoad(): void {
  22. let parentSize = this.node.parent.getContentSize();
  23. let selfSize = this.node.getContentSize();
  24. this.x_max = (parentSize.width - selfSize.width)/2;
  25. this.y_max = (parentSize.height - selfSize.height)/2;
  26. }
  27. gameUpdate(dt: number): void {
  28. let offset = this.destination.sub(this.node.getPosition());
  29. if(offset.mag() <= this.speed * dt) {
  30. this.node.setPosition(this.destination);
  31. }
  32. else{
  33. let dirction = offset.normalize();
  34. this.node.x += this.speed * dt * dirction.x;
  35. this.node.y += this.speed * dt * dirction.y;
  36. }
  37. cc.log('@@ -- ', this.node.position.toString());
  38. this.node.x = Math.max(-this.x_max , this.node.x);
  39. this.node.x = Math.min(this.x_max , this.node.x);
  40. this.node.y = Math.max(-this.y_max , this.node.y);
  41. this.node.y = Math.min(this.y_max , this.node.y);
  42. }
  43. isDone(): boolean {
  44. return this.node.x == this._destination.x && this.node.y == this._destination.y;
  45. }
  46. }