1.cocos2d-x引擎的坐标系

在这之前我们先了解一下cocos2d-x引擎中的坐标系:

(1)openGL & openGL ES坐标系。这也是触摸事件中使用的坐标系,原点在左上,坐标值往右下方向递增。

(2)世界坐标系。这是cocos2d-x中使用的坐标系。也是我们平常编程所使用的,原点在左下,坐标值往右上方向递增。

(3)节点坐标系。这是一个相对坐标系,是指节点一旦移动,和它关联的节点也会随之移动。

(1)和(2)之间的转换是我们经常要处理的,其实它们的纵坐标和即是屏幕的高。当然Cocos2d-x也提供了非常方便的转换函数给我们使用。

 

CCPoint CCDirector::convertToGL(const CCPoint& uiPoint)
{
CCSize s = m_obWinSizeInPoints;
float newY = s.height - uiPoint.y;

return ccp(uiPoint.x, newY);
}

CCPoint CCDirector::convertToUI(const CCPoint& glPoint)
{
CCSize winSize = m_obWinSizeInPoints;
float oppositeY = winSize.height - glPoint.y;

return ccp(glPoint.x, oppositeY);
}


 


2.锚点

锚点在cocos2d-x引擎中是个很重要的概念,可以这么理解,锚点就是一个基准点。比如我们要把一个100x200的长方形放在屏幕上。

第一种情况

 

m_sprite->setAnchorPoint(ccp(0.5,0.5));
m_sprite->setPosition(ccp(300,300));


 

第二种情况

 

 

m_sprite->setAnchorPoint(ccp(0,0));
m_sprite->setPosition(ccp(300,30));


[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了_背景图

3.飞机要起飞了

 

不,背景要起飞了。

这里我们采用的办法是让2张一样的背景循环进行滚动,然后通过每次滚动的时间间隔和像素间隔来控制背景滚动的速度,也就是飞机飞行的速度。注意图1和图2是一模一样的,所以最后一步是用图1替换了图2。记住图片的高度必须比屏幕高度高,不然在图2走到(0,0)的时候会有黑边出现。。。

[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了_加载_02

 

bool GameLayer::init()
{
bool bRet=false;
do
{
CC_BREAK_IF(!CCLayer::init());

//png加入全局cache中
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("shoot_background.plist");

//加载background1
background1=CCSprite::create(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("background.png"));
background1->setAnchorPoint(ccp(0,0));
background1->setPosition(ccp(0,0));
this->addChild(background1);

//加载background2
background2=CCSprite::create(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("background.png"));
background2->setAnchorPoint(ccp(0,0));
background2->setPosition(ccp(0,background2->getContentSize().height-2));//这里减2的目的是为了防止图片交界的黑线

this->addChild(background2);

//执行任务计划,实现背景滚动
this->schedule(schedule_selector(GameLayer::backgroundMove),0.01f);

bRet=true;
} while (0);
return bRet;
}

//背景滚动
void GameLayer::backgroundMove(float dt)
{
background1->setPositionY(background1->getPositionY()-2);
background2->setPositionY(background1->getPositionY()+background1->getContentSize().height-2);
if (background2->getPositionY()==0)//要注意因为背景图高度是842,所以每次减去2最后可以到达0,假如背景高度是841,那么这个条件永远达不到,滚动失败
{
background1->setPositionY(0);
}
}


调试运行,背景滚动的还不错,比较流畅。