转自:http://blog.csdn.net/xiaoxiangp/article/details/7707353
研究了一下自带例子中,有一项是根据点组成曲线或直线来移动精灵..觉得蛮有用处的,所以尝试并整理了一下,和大家分享一下
1. 首先创建好了工程后修改.h文件,重载了draw函数..用于画路径.这是一个虚函数,虽然没有加virtual关键字,C++默认是可以省略的..
- class HelloWorld : public cocos2d::CCLayer
- {
- public:
- virtual bool init();
- // there's no 'id' in cpp, so we recommand to return the exactly class pointer
- static cocos2d::CCScene* scene();
- void draw();
- // implement the "static node()" method manually
- LAYER_CREATE_FUNC(HelloWorld);
- private:
- cocos2d::CCPointArray *m_pArray;
- };
2. 由于是直接显示效果,所以直接就写在init函数中了:
- bool HelloWorld::init()
- {
- bool bRet = false;
- do
- {
- CC_BREAK_IF(! CCLayer::init());
- CCSize s = CCDirector::sharedDirector()->getWinSize();
- //以下是蓝色方块
- CCSprite* blue = CCSprite::create("blue.png");
- CC_BREAK_IF(!blue);
- blue->setPosition(ccp(50,50));
- this->addChild(blue);
- //创建一个点数组..
- CCPointArray * array = CCPointArray::create(20);
- //添加控制点...依次添加就可以
- array->addControlPoint(ccp(0, 0));
- array->addControlPoint(ccp(s.width/2-30, 0));
- array->addControlPoint(ccp(s.width/2-30, s.height-80));
- array->addControlPoint(ccp(0, s.height-80));
- array->addControlPoint(ccp(0, 0));
- //create(参数1:持续时间, 参数二:点数组,参数3:张力,可以理解为惯性,数值越大,惯性越大)
- CCCardinalSplineBy *action = CCCardinalSplineBy::create(6, array, 7);
- CCActionInterval *reverse = action->reverse();//创建一个相反动作
- //创建一个序列动作..
- CCFiniteTimeAction *seq = CCSequence::create(action, reverse, NULL);
- blue->runAction(seq);
- //以下是红色方块
- CCSprite *red = CCSprite::create("red.png");
- CC_BREAK_IF(!red);
- red->setPosition(ccp(s.width/2, 50));
- this->addChild(red);
- CCCardinalSplineBy *action2 = CCCardinalSplineBy::create(3,array,1);
- CCActionInterval *reverse2 = action2->reverse();
- CCFiniteTimeAction *seq2 = CCSequence::create(action2,reverse2,NULL);
- red->runAction(seq2);
- m_pArray = array;//把点数组中的内容赋值给成员变量,用于绘制路径
- array->retain();//使内容保持
- bRet = true;
- } while (0);
- return bRet;
- }
3. 重写draw()函数,实现路径绘制,当然也可以不写,那样精灵移动你就找不着北了...
值得注意的是那个张力值(惯性)在画线的时候..要一致,不然画出来的线就不是实际移动路径了..
- //重载绘制函数,用于绘制移动路径
- void HelloWorld::draw()
- {
- // move to 50,50 since the "by" path will start at 50,50
- kmGLPushMatrix();//这个的意思不是很懂,猜测是打开绘制
- kmGLTranslatef(50, 50, 0);//设置位置,(x,y,z)
- ccDrawCardinalSpline(m_pArray, 7, 100);//根据点与张力来画线(参数1:点数组,参数2:张力值,参数三:精度,指的是线段的精细程度,越大分段越多,越精细)
- kmGLPopMatrix();//停止绘制
- CCSize s = CCDirector::sharedDirector()->getWinSize();
- kmGLPushMatrix();
- kmGLTranslatef(s.width/2, 50, 0);
- ccDrawCardinalSpline(m_pArray, 1, 100);
- kmGLPopMatrix();
- }
这个功能比较简单..但是学到了点数组的使用..这用起来感觉像Vector向量数组..初始化一个大小后,add一个就加一个在最后..
上面添加了五个点..参数写5是没问题的..
用到的图片:
by...XX