45 lines
1.5 KiB
TypeScript
45 lines
1.5 KiB
TypeScript
import { _decorator, Component, Vec3 } from 'cc';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('RopeMovement')
|
|
export class RopeMovement extends Component {
|
|
@property
|
|
distance: number = 10; // 控制移动的总距离
|
|
|
|
@property
|
|
loopDuration: number = 5; // 循环一次的时长,单位为秒
|
|
|
|
private initialPosition: Vec3 = new Vec3(); // 初始位置
|
|
private movingRight: boolean = true; // 控制移动方向
|
|
private elapsedTime: number = 0; // 已经过的时间
|
|
|
|
start() {
|
|
// 记录初始位置
|
|
this.initialPosition.set(this.node.position);
|
|
}
|
|
|
|
update(deltaTime: number) {
|
|
// 更新已经过的时间
|
|
this.elapsedTime += deltaTime;
|
|
|
|
// 根据已经过的时间,计算循环一次的比例
|
|
const loopProgress = this.elapsedTime / this.loopDuration;
|
|
|
|
// 根据比例计算当前位置与初始位置的距离
|
|
const currentDistance = this.distance * loopProgress;
|
|
|
|
// 根据移动方向和速度更新小人的位置
|
|
if (this.movingRight) {
|
|
this.node.position = this.initialPosition.add3f(currentDistance, 0, 0);
|
|
} else {
|
|
this.node.position = this.initialPosition.add3f(-currentDistance, 0, 0);
|
|
}
|
|
|
|
// 如果已经过了循环一次的时长,重置已经过的时间并改变移动方向
|
|
if (this.elapsedTime >= this.loopDuration) {
|
|
this.elapsedTime = 0;
|
|
this.movingRight = !this.movingRight;
|
|
}
|
|
}
|
|
}
|