无限滚动背景
创建一个MovingSceneBg节点-存放两个背景图
创建脚本挂在MovingSceneBg节点上
@property(Node)
bg01: Node = null // 背景一的位置 Position x:0 y:1280
@property(Node)
bg02: Node = null //背景二的位置 Position x:0 y:0
_bgSpeed = 100; //滚动速度
_bgMovingRange = 1280;//滚动回来的位置
//在update中调用
private moveBackground(deltaTime: number) {
this.bg01.setPosition(v3(0, this.bg01.getPosition().y + this._bgSpeed * deltaTime, 0))
this.bg02.setPosition(v3(0, this.bg02.getPosition().y + this._bgSpeed * deltaTime, 0))
//判断是否在可见位置
if (this.bg01.position.y > this._bgMovingRange) {
this.bg01.setPosition(v3(0, this.bg02.position.y - this._bgMovingRange, 0));
} else if (this.bg02.position.y > this._bgMovingRange) {
this.bg02.setPosition(v3(0, this.bg01.position.y - this._bgMovingRange, 0));
}
}
向下滚动
@property(Node)
bg01: Node = null
@property(Node)
bg02: Node = null
_bgSpeed = 1000;
_bgMovingRange = -1280;
start() {
this._init();
}
update(deltaTime: number) {
this.moveBackground(deltaTime);
}
//位置重置
private _init() {
this.bg01.setPosition(v3(0, 0, 0))
this.bg02.setPosition(v3(0, this._bgMovingRange, 0))
}
private moveBackground(deltaTime: number) {
this.bg01.setPosition(v3(this.bg01.getPosition().x, this.bg01.getPosition().y - this._bgSpeed * deltaTime, 0));
this.bg02.setPosition(v3(this.bg02.getPosition().x, this.bg02.getPosition().y - this._bgSpeed * deltaTime, 0));
if (this.bg01.getPosition().y <= this._bgMovingRange) {
this.bg01.setPosition(v3(this.bg01.getPosition().x, this.bg02.getPosition().y - this._bgMovingRange, 0));
}
if (this.bg02.getPosition().y <= this._bgMovingRange) {
this.bg02.setPosition(v3(this.bg02.getPosition().x, this.bg01.getPosition().y - this._bgMovingRange, 0));
}
}