vector<Sprite*> m_vecBg; //容器存放图片
//创建背景
void createBg();
:m_fSpeed(-75) //向下运动
void CBackground::createBg()
{
//获取窗口的大小和原点
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//创建多张图片,并给定位置
//string arrPng[] = {"Image/Map1.png","Image/Map2.png"}; //法1 把图片存到数组中
char szName[32] = {}; // 给定的字符串长度要够,否则会发生越界中断 法2
float fy = 0;
//实现效果:不同关卡背景图不同
//因为有了关卡 i< pLevelDt->vecBgImage.size()
//先获取关卡Id(在动态数据GameData里)
int nLevelId = CDynamicData::getInstance()->getLevelId();
//通过Id 获取关卡数据
CLevelDt* pLevelDt = CConfigMgr::getInstance()->getData("LevelDtMgr")->getDataByID<CLevelDt*>(nLevelId);
//遍历容器,拿到背景图
for (int i = 0; i < pLevelDt->vecBgImage.size(); i++)
{
//Sprite* pBg = pLevelDt->vecBgImage[i]; //错,是创建不是遍历 !!! 要用create
//Sprite* pBg = Sprite::create(arrPng[i]); //法1
//sprintf_s(szName, "Image/Map%d.png", i + 1); //法2,格式化字符串
//Sprite* pBg = Sprite::create(szName);
string strName = pLevelDt->vecBgImage[i];
Sprite* pBg = Sprite::create(strName);
//锚点为下方中心点
pBg->setAnchorPoint(Vec2(0.5, 0));
//图片位置(每一张接在前一张的上面)
pBg->setPosition(origin.x + visibleSize.width / 2, fy);
fy += pBg->getContentSize().height;
//加入当前场景
this->addChild(pBg);
//别忘了压入容器
m_vecBg.push_back(pBg);
}
}
void CBackground::update(float fDelta)
{
//滚动
for (int i = 0; i < m_vecBg.size(); i++)
{
Sprite* pBg = m_vecBg[i];
float fy = pBg->getPositionY();
//fy--;
fy += m_fSpeed* fDelta; //偏移量=速度*时间
pBg->setPositionY(fy);
}
//检测越界
for (int i = 0; i < m_vecBg.size(); i++)
{
Sprite* pBg = m_vecBg[i]; //遍历容器,拿到图片
float fy = pBg->getPositionY(); //拿到纵坐标
//越界
if (fy <= -pBg->getContentSize().height)
{
//拿到最后一张
int nLastIndex = (i + m_vecBg.size() - 1) % m_vecBg.size(); //公式
Sprite* pLastPng = m_vecBg[nLastIndex];
//接到最后一张的后面(纵坐标+前一张背景图的高度)
pBg->setPositionY(pLastPng->getPositionY() + pLastPng->getContentSize().height);
}
}
}