Cocos Creator3.8 项目实战(五)背景无限滚屏效果如何实现

在游戏中,我们经常会实现背景无限滚动的效果。那这些效果是怎么实现的呢?

原理很简单,就是使用多张背景图,每张图,每一帧都同时移动,当图移出屏幕外时,将其位置设置到下一张图的初始位置,最后一张图位置设置为第一张图的初始位置,如此循环即可。

下面以 实现背景 1920*1080 的背景图,垂直方向无限滚动为例,进行详细说明。

⚠️ 文末附 BgMoveView.ts 完整源码, 可直接拿去使用。

具体实现方法:

step 1 ,在cocoscrearor 资源管理器中,添加多张背景图资源,并设置为sprite-frame类型。

注意:最好每张图的尺寸一致。

如下:

step 2 ,在cocoscrearor 层级管理器中,首先添加 bgNode 节点,用于背景图的根节点,然后再添加多个sprite节点 ,并设置sprite frame 资源 以及位置。

注意位置:

第一张图 0 ,0

第一张图 0 ,-1080

第三张图 0 ,-1080 *2

第四张图 0 ,-1080 *3

第五张图 0 ,-1080 *4

第六张图,以此类推...

step 3 ,为根节点 设置蒙版(Mask)组件。

step 4 ,为bgNode节点 挂载背景滚动脚本,并配置背景节点数组、滚动速度。

Step 5 、脚本 BgMoveView.ts 完整源码

复制代码
/**
 * 
 * 背景无限滚屏效果实现
 *
 * 
 * */

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

@ccclass('BgMoveView')
export class BgMoveView extends Component {
    
	/**背景数组 */
    @property({type: Node})
	bgList:Node[] = [];

	/**移动速度 */
	@property({type: Number})
	moveSpeed:number = 200;

	/**背景图片滚出屏幕的位置*/
    bottomPosition:number = 0;

	/**背景图片高度*/
	bgHeight:number = 0;

	onLoad () {
	
		/**注意是负值*/
		this.bottomPosition = -this.bgList[0].getComponent(UITransform).height;
		this.bgHeight = this.bgList[0].getComponent(UITransform).height;
	}

    start() {

    }

    update(deltaTime: number) {
        
		for(let i = 0; i < this.bgList.length; i++) {

            /**达到触发条件,改变背景图片位置*/ 
			if(this.bgList[i].position.y <= this.bottomPosition) {
                this.bgList[i].setPosition(this.bgList[i].position.x,
					this.bgList[i+1<this.bgList.length?i+1:0].position.y + this.bgHeight);
			}

       		/**背景的移动*/  
			this.bgList[i].setPosition(this.bgList[i].position.x, this.bgList[i].position.y - this.moveSpeed*deltaTime);
		}
	}
}
相关推荐
GHL2842710902 分钟前
安装chrome浏览器
前端·chrome
谙忆10247 分钟前
WebCodecs 实战:用 ImageDecoder 和 VideoFrame 在浏览器里做硬件加速的帧处理
前端
JerrySir9 分钟前
密码没泄露,2FA 也没失效:Chrome 146 为什么还要让 Cookie“搬不走”?
前端
小蚂蚁i10 分钟前
React Hooks 原理深度解析:从会用到真正懂
前端·react.js
触底反弹15 分钟前
Vue 实战:手把手教你实现 ChatGPT 同款打字机效果
前端·javascript·人工智能
BreezeJiang18 分钟前
Vue 3 流式输出实战:ReadableStream + DeepSeek API 实现打字机对话
前端
用户EasyAdminBlazor24 分钟前
EasyAdminBlazor 第十篇:数据导入导出——批量处理不再麻烦
前端·后端
饮茶三千26 分钟前
电子保函模板编辑器实战二:HTML→FTL 编译转换的设计与实现
前端·vue.js·设计模式
ricardo197331 分钟前
SSR / SSG 性能对比:Next.js 三种渲染模式实测数据
前端·面试
LuminousCPP33 分钟前
C 语言集中实践全记录:顺序表 + 单链表原理实现与通讯录项目实战【附可运行源码】
c语言·开发语言·数据结构·经验分享·笔记