多层背景视差滚动Parallax Scrolling

基础原理

视差效果的核心是:不同图层的移动速度不同(距离玩家越远的图层移动越慢)

实现步骤

  1. 准备分层背景
  • 将背景拆分成多个图层,按层级排序
  1. 挂载视差脚本
  • 为每个图层添加自定义脚本,控制其移动速度
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;
    }
}
  1. 进阶优化
  • 如果使用cocos creator 3.x的摄像机组件,可以直接监听摄像机的位移事件
javascript 复制代码
// 监听摄像机移动
cc.Camera.main.node.on('position-changed', (pos: cc.Vec3) => {
    this.updateLayerPosition(pos.x);
});
  • 对于超长地图,可以动态加载/卸载背景块(根据摄像机视口位置)
相关推荐
VaJoy13 天前
Cocos Creator Shader 入门 ⑺ —— 图层混合样式的实现与 Render Texture
cocos creator
VaJoy15 天前
Cocos Creator Shader 入门 ⑹ —— 灰阶、反色等滤镜的实现
cocos creator
VaJoy17 天前
Cocos Creator Shader 入门 ⑸ —— 代码复用与绿幕抠图技术
cocos creator
VaJoy19 天前
Cocos Creator Shader 入门 ⑷ —— 纹理采样与受击闪白的实现
cocos creator
VaJoy20 天前
Cocos Creator Shader 入门 ⑶ —— 给节点设置透明度
cocos creator
VaJoy22 天前
Cocos Creator Shader 入门 (2) —— 给节点染色
cocos creator
VaJoy23 天前
Cocos Creator Shader —— 附录
cocos creator
似水流年wxk1 个月前
cocos creator使用jenkins打包微信小游戏,自动上传资源到cdn,windows版运行jenkins
运维·jenkins·cocos creator
成长ing121383 个月前
点击音效系统
前端·cocos creator