cocos开发2d游戏的时候,模拟背景无限循环移动的思路和实现方法

241 阅读1分钟

可以看到背景是一直在移动的,其实这里是使用两张图片拼接在一起实现的类似无线循环的效果,就像一个滚筒一样,将两张一摸一样可以拼接的两张图片衔接在一起,然后贴在滚筒上,当滚筒一直滚动,面向滚筒正方向的你,其实就可以看到类似无限循环的效果。

核心滚动代码

在update函数中,每一帧都要移动两张背景图的位置向下移动,当某一张图移动到屏幕外的时候,就立刻马上设置y轴的位置,让它回到另外一张图衔接的位置


    update(deltaTime: number) {
        // 背景上下连续移动
        this.bg.setPosition(
            this.bg.position.x,
            this.bg.position.y - this.speed * deltaTime,
            this.bg.position.z
        )
        this.bg2.setPosition(
            this.bg2.position.x,
            this.bg2.position.y - this.speed * deltaTime,
            this.bg2.position.z
        )

        // 如果背景移动到屏幕外,则快速将其移动到屏幕内
        if (this.bg.position.y < -852) {
            this.bg.setPosition(
                this.bg2.position.x,
                this.bg2.position.y + 852,
                this.bg2.position.z
            )
        }
        // 如果背景2移动到屏幕外,则快速将其移动到屏幕内
        if (this.bg2.position.y < -852) {
            this.bg2.setPosition(
                this.bg.position.x,
                this.bg.position.y + 852,
                this.bg.position.z
            )
        }
    }

所有代码:

import { _decorator, Component, Node } from 'cc'
const { ccclass, property } = _decorator

@ccclass('bgrun')
export class bgrun extends Component {
    @property(Node)
    public bg: Node = null

    @property(Node)
    public bg2: Node = null

    // 速度
    @property(Number)
    public speed: number = 10

    start() {
        console.log('bgrun')
    }

    update(deltaTime: number) {
        // 背景上下连续移动
        this.bg.setPosition(
            this.bg.position.x,
            this.bg.position.y - this.speed * deltaTime,
            this.bg.position.z
        )
        this.bg2.setPosition(
            this.bg2.position.x,
            this.bg2.position.y - this.speed * deltaTime,
            this.bg2.position.z
        )

        // 如果背景移动到屏幕外,则快速将其移动到屏幕内
        if (this.bg.position.y < -852) {
            this.bg.setPosition(
                this.bg2.position.x,
                this.bg2.position.y + 852,
                this.bg2.position.z
            )
        }
        // 如果背景2移动到屏幕外,则快速将其移动到屏幕内
        if (this.bg2.position.y < -852) {
            this.bg2.setPosition(
                this.bg.position.x,
                this.bg.position.y + 852,
                this.bg.position.z
            )
        }
    }
}