cocos2dx中的实现地图卷动的两种方式

在游戏当中,实现地图卷动是最基本的功能,具体的实现的方法,大致有两类:

方法一:加载两张图片,轮流显示,

优点: 1.无论是地图上下卷动,还是左右卷动都可以

2.支持各种图片,(png,jpg...)

缺点: 1.前提是会创建两个背景精灵,稍微浪费内存,

2.且要求作为背景地图的图片需要大于窗口的大小

/*
*给游戏主战斗场景添加滚动的背景地图
*/
void GameMainScene::addbackground()
{
Texture2D* texture = TextureCache::getInstance()->getTextureForKey("groundLevel.jpg");
_spriteBgH = Sprite::createWithTexture(texture);
_spriteBgH->setAnchorPoint(Vec2(, ));
_spriteBgH->setPosition(, );
this->addChild(_spriteBgH); _lowPos = -_spriteBgH->getContentSize().height;//必须设置地图的下限,且必须使用contentsize(),不能用winSize
//_lowPos = -winSize.height;//错误 _spriteBgL = Sprite::createWithTexture(TextureCache::getInstance()->getTextureForKey("groundLevel.jpg"));
_spriteBgL->setAnchorPoint(Vec2(, ));
_spriteBgL->setPosition(, _lowPos);
this->addChild(_spriteBgL); this->scheduleUpdate();
} /*
*帧循环定时器,实现背景地图的卷动
*/
void GameMainScene::update(float dt)
{
_spriteBgH->setPositionY(_spriteBgH->getPositionY() - );//地图向下移动的速度
_spriteBgL->setPositionY(_spriteBgL->getPositionY() - );//每帧向下移动2个像素 if (_spriteBgL->getPositionY() < _lowPos)//判断下面的地图是否移出下限
{
_spriteBgL->setPositionY(_spriteBgH->getPositionY()+_spriteBgH->getContentSize().height);//如果移出,则直接设置到第一张地图的上面
}
if (_spriteBgH->getPositionY() < _lowPos)
{
_spriteBgH->setPositionY(_spriteBgL->getPositionY()+_spriteBgL->getContentSize().height);
}
}

方法二:使用Texture2D::TexParams,只需要一张图片,重复绘制,设置textureRect,即可

优点:1.只需要加载一张图片,更省内存

缺点:1.需要额外设置textureRect的大小,且支持的图片类型有限(支持部分jpg),png类型的未试过

/*
* 卷动背景地图
*/
void GameMainScene::addMoveBackground()
{
xScroll = ;
sprite1 = Sprite::create("groundLevel.jpg");//只需要创建一个背景精灵 sprite1->setAnchorPoint(Vec2(, ));
sprite1->setPosition(, );
addChild(sprite1);
Texture2D::TexParams texRepeat = { GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_REPEAT };//这些openGL的参数不是对所有的图片类型都适合
sprite1->getTexture()->setTexParameters(texRepeat);//设置精灵渲染时获得纹理的方式为:重复渲染
schedule(schedule_selector(GameMainScene::moveBackground), 0.01f);
}
/*
*  通过改变y轴的坐标,实现TextureRect渲染矩形的区域的改变,实现地图卷动的视觉效果
*/
void GameMainScene::moveBackground(float dt)
{
sprite1->setTextureRect(Rect(, (xScroll-=), winSize.width, winSize.height+)); //y轴的坐标每帧都递减(向下卷动),如果是递增,则地图向上卷动,如果是x轴坐标变化,则地图左右移动
}
上一篇:glade2支持C++代码的输出(3)


下一篇:extjs 优化小建议