开发中常常需要做一些测试,该脚本用Tween实现了物体的随机移动,可以按需挂载。
export default class MoveScript extends Laya.Script {
private moveSpeed: number = .05; // 移动速度
private rotationSpeed: number = 5; // 旋转速度
private _targetPos: Laya.Point = new Laya.Point();
private _spr: Laya.Sprite;
private _tween: Laya.Tween;
onEnable(): void {
this._tween = new Laya.Tween();
this._spr = this.owner as Laya.Sprite;
this.toNext();
}
private dis(start: { x, y }, end: { x, y }): number {
return Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2));
}
private toNext(): void {
this._targetPos.setTo(Math.random() * Laya.stage.width, Math.random() * Laya.stage.height);
this._tween.to(this._spr, { x: this._targetPos.x, y: this._targetPos.y }, this.dis(this._spr, this._targetPos) / this.moveSpeed, Laya.Ease.linearNone, Laya.Handler.create(this, this.toNext));
}
}