基础原理
视差效果的核心是:不同图层的移动速度不同(距离玩家越远的图层移动越慢)
实现步骤
- 准备分层背景
- 将背景拆分成多个图层,按层级排序
- 挂载视差脚本
- 为每个图层添加自定义脚本,控制其移动速度
scala
// ParallaxLayer.ts
const { ccclass, property } = cc._decorator;
@ccclass
export class ParallaxLayer extends cc.Component {
@property
public speedFactor: number = 0.5; // 速度系数(0~1)
private _camera: cc.Node; // 主摄像机(或跟随目标)
private _startPos: number; // 初始位置
start() {
this._camera = cc.find("Main Camera"); // 根据实际路径调整
this._startPos = this.node.x;
}
update() {
// 根据摄像机位置计算图层偏移
this.node.x = this._startPos + this._camera.x * this.speedFactor;
}
}
- 进阶优化
- 如果使用cocos creator 3.x的摄像机组件,可以直接监听摄像机的位移事件
javascript
// 监听摄像机移动
cc.Camera.main.node.on('position-changed', (pos: cc.Vec3) => {
this.updateLayerPosition(pos.x);
});
- 对于超长地图,可以动态加载/卸载背景块(根据摄像机视口位置)