Egret学习笔记 (Egret打飞机-3.实现背景循环滚动)
游戏背景里面的猪脚飞机看起来是一直在向前飞,但是实际上只是一个视觉差而已。
猪脚是出于不动的状态,背景从上到下滚动,然后让玩家觉得飞机在不停的往前飞。(当然这只是其中一种实现思路)
差不多就是这样,然后两张图片一直滚动,上面的图,滚动到最底下,马上又跑到最上面去,一直循环,就有了一个滚动的效果
然后我导入了一张背景图
然后重新打开我们的BgContent.ts文件,把里面的黑色背景的代码×掉,然后改为
bgbitmap1: egret.Bitmap;
bgbitmap2: egret.Bitmap;
public Init(): void {
var bg = RES.getRes("background_png");
this.bgbitmap1 = new egret.Bitmap(bg);
this.bgbitmap1.width = GameConfig.SceneW;
this.bgbitmap1.height = GameConfig.SceneH;
this.addChild(this.bgbitmap1)
this.bgbitmap2 = new egret.Bitmap(bg);
this.bgbitmap2.width = GameConfig.SceneW;
this.bgbitmap2.height = GameConfig.SceneH;
this.addChild(this.bgbitmap2)
}
-走到这一步,点击运行,可以看到屏幕背景成为了上边的那个背景图,然后,我们再来实现背景滚动
-首先我们先监听一下帧事件,在图片添加完成后监听
this.addEventListener(egret.Event.ENTER_FRAME,()=>{
},this)
-设置两张图片的位置,一张恰好显示到屏幕,一张就放到屏幕的上方,坐标为X为0Y为(0-屏幕的高度)
this.bgbitmap1.x = 0;
this.bgbitmap1.y = 0;
this.bgbitmap2.x = 0;
this.bgbitmap2.y = - GameConfig.SceneH;
-然后我们开始我们的背景滚动,在ENTER_FRAME事件里面,我们每一帧都移动一下背景图的坐标,然后背景图的坐标高于屏幕的坐标,那么就把图的坐标移动到(0,0-屏幕高度)的位置
this.bgbitmap1.y += this.bgSpeed;
if (this.bgbitmap1.y > GameConfig.SceneH) {
this.bgbitmap1.y = (0 - GameConfig.SceneH)
}
this.bgbitmap2.y += this.bgSpeed;
if (this.bgbitmap2.y > GameConfig.SceneH) {
this.bgbitmap2.y = (0 - GameConfig.SceneH)
}
然后点击运行,就可以看到如下的效果了
运行是能运行了,但是好像有一条碍眼的线偶尔会横着。。。我找了半天也不知道啥原因。。
最后我把背景图的高度设置长点。。。好像就没这个问题了
var bg = RES.getRes("background_png");
this.bgbitmap1 = new egret.Bitmap(bg);
this.bgbitmap1.width = GameConfig.SceneW;
this.bgbitmap1.height = GameConfig.SceneH+10;
this.addChild(this.bgbitmap1)
this.bgbitmap2 = new egret.Bitmap(bg);
this.bgbitmap2.width = GameConfig.SceneW;
this.bgbitmap2.height = GameConfig.SceneH;
this.addChild(this.bgbitmap2)
this.bgbitmap1.x = 0;
this.bgbitmap1.y = 0;
this.bgbitmap2.x = 0;
this.bgbitmap2.y = - GameConfig.SceneH+10;
分类:
Egret学习笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端