PushItem.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { _decorator, BoxCollider2D, Component, Node, PhysicsSystem2D, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('PushItem')
  4. export class PushItem extends Component {
  5. targetWidth: number = 500;
  6. //duration: number = 60.0;
  7. private speed: number = 2;
  8. start() {
  9. // this.init()
  10. }
  11. init(time) {
  12. let boxCollider2D = this.getComponent(BoxCollider2D)
  13. const startWidth = this.getComponent(UITransform).contentSize.width;
  14. const deltaWidth = this.targetWidth - startWidth;
  15. if (!time) {
  16. time = 1
  17. }
  18. // 计算每秒需要增加的宽度
  19. this.speed = deltaWidth / time;
  20. // let s = endPos.pushItem - this.getComponent(UITransform).contentSize.width;
  21. // this.speed = s / time
  22. }
  23. resize(dt: number) {
  24. // 计算这一帧需要增加的宽度
  25. const deltaWidth = this.speed * dt;
  26. // 获取当前宽度
  27. const uit = this.getComponent(UITransform);
  28. const currentWidth = uit.contentSize.width;
  29. // 更新宽度
  30. const newWidth = currentWidth + deltaWidth;
  31. // 如果已经达到目标宽度,停止更新
  32. if (newWidth >= this.targetWidth) {
  33. this.speed = 0; // 停止更新
  34. uit.setContentSize(this.targetWidth, uit.contentSize.height);
  35. } else {
  36. uit.setContentSize(newWidth, uit.contentSize.height);
  37. }
  38. this.updateCollider(newWidth);
  39. }
  40. //更新碰撞体
  41. updateCollider(width: number) {
  42. const collider = this.getComponent(BoxCollider2D);
  43. if (collider) {
  44. collider.size.width = width - 10;
  45. collider.offset.x = (width - 10) * 0.5;
  46. collider.apply();
  47. }
  48. }
  49. }