Creator2D横版游戏(2)背景图随主角移动
上次教程做好了人物左右走,这次来做背景移动
本次目标
1.背景图跟随角色移动
2.限制背景图移动范围,不出黑边

移动背景的脚本放在canvas上

说是背景在移动,实际上是移动相机
需要的属性
@property({displayName: "相机", tooltip: "相机", type: Node})
camera: Node = null;
@property({type: UITransformComponent})
canvas: UITransformComponent = null;
@property({displayName: "背景", tooltip: "背景", type: Node})
bg: Node = null;
@property({displayName: "角色", tooltip: "角色", type: Node})
player: Node = null;
所有逻辑都要写在update里面,防止穿帮
下面是相机移动的代码
update () {
// 左边四分之三屏幕位置
let left_3_4 = this.camera.position.x - (this.canvas.width / 4);
// 右边四分之三屏幕位置
let right_3_4 = this.camera.position.x + (this.canvas.width / 4);
// 如果到了右边四分之三屏幕位置
if (this.player.position.x >= right_3_4) {
// log("到了右边四分之三处");
// 相机跟随角色移动
this.camera.setPosition(new Vec3(this.player.position.x - (this.canvas.width / 4), 0, 1000));
}
// 如果到了左边四分之三屏幕位置
if (this.player.position.x <= left_3_4) {
// log("到了左边四分之三处");
// 相机跟随角色移动
this.camera.setPosition(new Vec3(this.player.position.x + (this.canvas.width / 4), 0, 1000))
}
}
浏览器一预览可不得了
出现两个大问题:
主角一直往左走背景都移动出黑边了
按钮也跟着背景向右移动了

先来解决按钮问题
目前只有一个相机拍游戏的画面,拍的都是Layer为UI_2D和UI_3D的节点
可是主角和背景并不是UI,一般的游戏都有两个相机,一个拍游戏画面,一个拍UI,这样游戏相机跟随角色移动后UI相机不会移动,UI就不会乱动了

把之前拍游戏画面的相机复制粘贴一份,改名为UI_Camera专门拍UI

在项目-项目设置-Layers中添加一个名为2D的Layer


设置好两个相机的可见Layer
Camera只拍2D(游戏画面)
UI_Camera只拍UI_2D和UI_3D(UI)


修改UI节点和它所有子节点的Layer

map和player的Layer为2D

浏览器看下效果,按钮不动了,接下来修复黑边bug

在move脚本的update加入下面的代码,限制相机的移动范围
// 背景左
let left_bg = this.bg.position.x - (this.bg.getComponent(UITransformComponent).width / 2);
// 背景右
let right_bg = this.bg.position.x + (this.bg.getComponent(UITransformComponent).width / 2);
// 相机左
let left_cam = this.camera.position.x - (this.canvas.width / 2);
// 相机右
let right_cam = this.camera.position.x + (this.canvas.width / 2);
// 如果相机到达左边缘
if (left_cam <= left_bg) {
// 一直在边缘
this.camera.setPosition(new Vec3(left_bg + (this.canvas.width / 2), 0, 1000))
// log("左边到达边缘");
}
// 如果相机到达右边缘
if (right_cam >= right_bg) {
// 一直在边缘
this.camera.setPosition(new Vec3(right_bg - (this.canvas.width / 2), 0, 1000))
// log("右边到达边缘");
}
这回就没黑边了

下期预告:Creator2D横版游戏(2)背景图随主角移动 | 单独相机拍UI
源码:https://gitee.com/propertygame/cocos-creator3.x-demos/tree/master/2Dhorizontal
技术交流Q群:1130122408
更多内容请关注微信公众号

3815

被折叠的 条评论
为什么被折叠?



