当前位置: 首页 > news >正文

Cocos Creator3.x设置动态加载背景图并且循环移动

效果图

在这里插入图片描述

项目结构

项目层级结构:
在这里插入图片描述
预制:
在这里插入图片描述

代码

import { _decorator, CCFloat, Component, Node, Sprite, instantiate, Prefab, assert, UITransform } from 'cc';
const { ccclass, property } = _decorator;/*** 背景脚本*/
@ccclass('Background')
export class Background extends Component {/** 背景图片预制体 */@property(Prefab)backgroundPrefab: Prefab;/** 背景图片移动速度 */@property(CCFloat)speed: number = 400;/** 背景图片高度 */private bgHeight: number;/** 背景节点数组 */private backgroundNodeArray: Node[] = [];/** 背景图片数量 */private readonly bgPicNum = 2;/*** 初始化背景图片数组*/private initBackgroundNodeArray() {for (let i = 0; i < this.bgPicNum; i++) {// 实例化预制体let bgNode = instantiate(this.backgroundPrefab);// 推入背景图片数组this.backgroundNodeArray.push(bgNode);// 挂载到背景根节点下this.node.addChild(bgNode);// 初始化背景图片高度this.initBackgroundHeight(bgNode);}}/***  初始化背景图片高度*/private initBackgroundHeight(bgNode: Node) {// 如果已初始化高度则返回if (!!this.bgHeight) {return;}// 获取背景图片精灵let bgSprite = bgNode.getComponent(Sprite);assert(!!bgSprite, "背景图片精灵未设置");// 动态读取背景图片高度this.bgHeight = bgSprite.spriteFrame.height;}/*** 初始化每个背景图片的位置*/private initEachBackgroundNodePosition() {for (let i = 0; i < this.backgroundNodeArray.length; i++) {let bgNode = this.backgroundNodeArray[i];// 图片位置按图片高度叠加bgNode.setPosition(bgNode.position.x, this.bgHeight * i);}}start() {assert(!!this.backgroundPrefab, "背景图片预制体未设置");// 初始化背景图片数组this.initBackgroundNodeArray();// 初始化背景图片位置this.initEachBackgroundNodePosition();}update(deltaTime: number) {// 更新背景图片位置this.updateBackgroundPosition(deltaTime);}/*** 更新背景图片位置* @param deltaTime 时间间隔*/private updateBackgroundPosition(deltaTime: number) {this.backgroundNodeArray.forEach(bgNode => {// 背景图片随时间下移bgNode.setPosition(bgNode.position.x, bgNode.position.y - this.speed * deltaTime);// 如果背景图片超出屏幕高度,则重置位置,接在上方if (bgNode.getPosition().y < -this.bgHeight) {// 计算帧运行到这里时,节点实际位置和背景图片高度的余数(如果图片下边界是-425,那么节点实际运行到这里时可能是-427了,就要把差值-2给补到平移的距离上去)let diff = bgNode.getPosition().y % this.bgHeight;// 重置图片位置bgNode.setPosition(bgNode.position.x, diff + this.bgHeight * (this.bgPicNum - 1));}});}
}

http://www.mrgr.cn/news/33349.html

相关文章:

  • 数字图像面积计算一般方法及MATLAB实现
  • 详解journalctl
  • WinRAR技巧:如何高效制作RAR分卷压缩文件
  • SIP信令的基本流程
  • 江协科技STM32学习- P16 实验-TIM输出比较(PWD驱动LED呼吸灯,舵机,直流电机)
  • VisionPro - 基础 - 模板匹配技术和在VP中的使用 - PMAlign - PatMax (5)- 非线性模板变形匹配
  • java自动解析apk安装包内容信息
  • 2.个人电脑部署MySQL,傻瓜式教程带你拥有个人金融数据库!
  • fastadmin数据库创建说明文档
  • Unet改进42:添加ACConv2d|使用一维非对称卷积来增强平方卷积核
  • Docker命令全解析:掌握容器化技术的基石
  • 9.22今日错题解析(软考)
  • java sdk下载,解决下载了java但是编译不了
  • 校园美食地图:Spring Boot实现的探索与分享平台
  • 本地电脑基于nginx的https单向认证和双向认证(自制证书+nginx配置)保姆级
  • ccfcsp-202403(1、2、3、4)
  • 初写MySQL四张表:(4/4)
  • 【红动中国-注册_登录安全分析报告】
  • atcoder abc372 启发式合并, dp
  • C++STL六大组件