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

cocos-js实现背景图的滚动

2015-11-13 11:58 295 查看
cocos-js实现背景图的滚动

var
ShuffLayer = cc.Layer.extend({

_turnImg1:
null
,

_turnImg2:
null
,

init:
function
(){

var
bRef =
false
;

if
(
this
._super()){

this
.steupView(sRes.backgroud);

bRef =
true
;

}

return
bRef;

},

steupView:
function
(fileName){

this
._turnImg1 =
new
cc.Sprite(fileName);

this
._turnImg1.setPosition(cc.p(
this
._turnImg1.getContentSize().width/2,
this
._turnImg1.getContentSize().height/2));

this
.addChild(
this
._turnImg1);


this
._turnImg2 =
new
cc.Sprite(fileName);

this
._turnImg2.setPosition(cc.p(
this
._turnImg2.getContentSize().width * 1.5,
this
._turnImg2.getContentSize().height /2));

this
.addChild(
this
._turnImg2);

},

onEnter:
function
(){

this
._super();

this
.scheduleUpdate();

},

update:
function
(dt){

//如果第一张背景图的中点到达屏幕下方背景图高度的一半的时候(也就是第一张图片移除图片下面的时候)重新设置他的位置到屏幕上面,图片下边缘跟手机屏幕上边缘重合-1个像素

if
(
this
._turnImg1.getPositionX()<=-
this
._turnImg1.getContentSize().width/2) {
  
this
._turnImg1.setPosition(cc.p(
this
._turnImg1.getContentSize().width
* 1.5 -1 ,
this
._turnImg1.getContentSize().height/2));

}
else
{
//如果还没需要换位置就让他向下移动一个像素
   
this
._turnImg1.setPosition(cc.pAdd(
this
._turnImg1.getPosition(), cc.p(-1,0)));

}

//如果第二张背景图移出屏幕最下方则重新设置他的位置在屏幕的最上方

if
(
this
._turnImg2.getPositionX() <= -
this
._turnImg2.getContentSize().width / 2) {

this
._turnImg2.setPosition(cc.p(
this
._turnImg2.getContentSize().width * 1.5 -1,
this
._turnImg2.getContentSize().height / 2));

}
else
{
//向下移动
  
this
._turnImg2.setPosition(cc.pAdd(
this
._turnImg2.getPosition(), cc.p(-1,0)));

}

}

});

ShuffLayer.create =
function
() {

var
ly =
new
ShuffLayer();

if
(ly && ly.init()){

return
ly;
}
return
null
;
};

ShuffLayer.scene =
function
() {

var
sc =
new
cc.Scene();

sc.addChild(ShuffLayer.create());

return
sc;
};

函数源码cc.pAdd = function (v1, v2) {
return cc.p(v1.x + v2.x, v1.y + v2.y);};

函数源码cc.pSub = function (v1, v2) {

return cc.p(v1.x - v2.x, v1.y - v2.y);};
实战代码练习

ctor:function(){

this._super();

size=cc.winSize;

sprite=new cc.Sprite(res.runbg);

sprite.attr({

x:sprite.getContentSize().width/2,

y:sprite.getContentSize().height/2

});

this.addChild(sprite,1);

sprite2=new cc.Sprite(res.runbg2);

sprite2.attr({

x:sprite2.getContentSize().width*1.5,

y:sprite2.getContentSize().height/2

});

this.addChild(sprite2,0);

this.schedule(this.SpriteMove, 0.1);},

SpriteMove:function(){

if (sprite.getPositionX()<=-sprite.getContentSize().width/2) {sprite.setPositionX(sprite.getContentSize().width*1.5-18);}

else{

sprite.setPositionX(sprite.getPositionX()-10);}

if (sprite2.getPositionX()<=-sprite2.getContentSize().width/2) {

sprite2.setPositionX(sprite.getContentSize().width*1.5);}else {sprite2.setPositionX(sprite2.getPositionX()-10);}}

在运行的过程中,图片的尺寸设计容易出现问题,要根据图片的像素大小对其进行更改!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: