您的位置:首页 > 移动开发 > Cocos引擎

【用Cocos Creator给暗恋的女生写一个游戏(7)】——(Run Game)背景移动

2016-08-29 07:47 543 查看
新建CameraManager.js添加到在Game的子节点CameraManager下

CameraManager.js

cc.Class({
extends: cc.Component,

properties: {
far:cc.Node,
farRelSpeed:0,//相对主角移动速度
farOffX:0,//循环滚动距离
ground:cc.Node,
groundRelSpeed:0,
groundOffX:0,
pipeLayer:cc.Node,
layerRelSpeed:0,
},

init: function (game) {
this.game = game;
this.oFarX = this.far.x;
this.oGroundX = this.ground.x;
},

moveBg: function(distance){
this.far.x -= distance * this.farRelSpeed;
if(this.far.x < (this.oFarX - this.farOffX)){
this.far.x = this.oFarX;
}
this.ground.x -= distance * this.groundRelSpeed;
if(this.ground.x < (this.oGroundX-this.groundOffX)){
this.ground.x = this.oGroundX;
}
this.pipeLayer.x -= distance * this.layerRelSpeed;
},
});




修改Game.js

var Player = require("Player");
var CameraManager = require("CameraManager");
cc.Class({
extends: cc.Component,

properties: {
player:Player,
cameraManager:CameraManager,
},

onLoad: function () {
//返回键返回菜单
cc.eventManager.addListener({
event: cc.EventListener.KEYBOARD,
onKeyPressed: function(keyCode, event) {
if(keyCode == cc.KEY.back){
cc.director.loadScene('Menu');
}
}
}, this.node);
this.startGame();
},

startGame: function(){
this.cameraManager.init(this);
this.player.init(this);
},

stopGame: function(){

},

});


修改Player.js

...
update: function (dt) {
if(this.state != STATE.NONE && this.state != STATE.DEAD){
this.speedY -= this.gravity * dt;
this.node.y += this.speedY * dt;
if(this.node.y <= this.groundY){
this.node.y = this.groundY;
}
this.game.cameraManager.moveBg(this.speedX * dt);
}
},
...


下面我要用我超强的逻辑思维给大家解释一下这个背景是怎么移动的

咳咳

我们知道每一次调用update方法,player的位置就会根据相应属性更新,而背景的移动应该跟player的移动相关,(这里我们可能要讲一下爱因斯坦的相对论,但可能讲完就下课了,所以不讲了…)我们需要知道player往前移动,背景就要往后移动,它们的速度是相反的。

还有远景和近景的移动速度不同,远处的移动速度要慢一些(那位举“坐火车”的例子的同学很聪明)

所以我们在CameraManager里设置了far相对player的速度 farRelSpeed 和ground相对于player的速度 groundRelSpeed 以及 layerRelSpeed ,因为ground,pipeLayer和player是在同一平面的,所以他们的相对速度都设为1,far节点较远,设为0.2

还有两个属性farOffX和groundOffX,他们是记录两个节点循环滚动距离的,因为我们的背景只有两张图片,需要循环显示,那个farOffX = 1000是计算出来的,留给同学们当作业,做完明天班长收一下

最后我们要把上次没用到的Player的speedX填上数值



通过这么巧妙的设置,我们就可以随便更改主角的速度而不用管背景的移动速度了,因为背景会随着主角速度动态调整

看一下效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐