最近项目做一个需要背景无限滚动,适用飞机,跑酷类型无限背景滚动等游戏,在网上找了一些例子,发现都犯严重的错误,就是滚动不和时间挂钩,会看到卡顿现象。每一帧+速度,正确来是s =v*dt,v速度,dt每一帧时间。
原理
现有一张图片,并排到一起是无缝衔接,假设你的分辨率是1280*720,用的图片长度是1552,如放一张图片,是足够长度的,至于为啥要是为了并排的图,能在移动时候,出现短暂黑的。
- 两个精灵分别A B 都是用同一张图片
- AB 同时移动 speed*dt,这里注意一定要乘时间
- 当B的位置移动到<0.0f时(表示后面的图片完全在屏幕上,A已移动到屏幕外面),把A放到B后面,这个时候就是BA。然后又到A移到<0.0f。
滚动代码
资源和图:http://pan.baidu.com/s/1mf2WY
BgScroll.h
#ifndef BGSCROLL_H
#define BGSCROLL_H
#include "cocos2d.h"
using namespace cocos2d;
class BgScroll :public Node
{
public:
BgScroll();
virtual ~BgScroll();
CREATE_FUNC(BgScroll);
private:
void update(float dt);
Sprite* _sprite[2];
float speed;
float tex_length;
};
#endif
BgScroll.cpp
#include "BgScroll.h"
BgScroll::BgScroll():
speed(60.0f)
{
auto tex = Director::getInstance()->getTextureCache()->addImage("taiko-bg.png");
tex_length = tex->getPixelsWide();
for (int i = 0; i < 2; ++i)
{
Sprite* node = Sprite::createWithTexture(tex);
node->setAnchorPoint(Vec2(0, 0));
this->addChild(node);
node->setPosition(i*Vec2(tex_length, 0));
_sprite[i] = node;
}
this->scheduleUpdate();
}
BgScroll::~BgScroll()
{
}
void BgScroll::update(float dt)
{
for (int i = 0; i < 2; ++i)
{
auto node = _sprite[i];
node->setPositionX(node->getPositionX() - speed*dt);
}
float x1 = _sprite[0]->getPositionX();
float x2 = _sprite[1]->getPositionX();
if (x2 < 0.0f)
{
_sprite[0]->setPositionX(x2 + tex_length);
std::swap(_sprite[0], _sprite[1]);
}
}
使用方法
auto _bg_scroll = BgScroll::create();
this->addChild(_bg_scroll);
总结
在游戏里面的任何动作,都需要*时间,因为每一帧的时间不是固定的,以前在某段时间会卡顿一下。

