cocos2dx下的曲线拉抻 以及 曲线连接多点
|
先上图,就是这种效果
做到这种效果的第一个难点是将图片按曲线路径去拉伸并传过固定的点去绘制曲线 所幸已经有人为我们写好了算法,这里http://discuss.cocos2d-x.org/...,谢谢这位大神! 把里面的cpp文件和h文件下载下来放进项目里就好,接下来就是怎么去用 if(auto spline = TexturedSpline::create(path,10,"brick.jpg")
{
addChild(spline);
spline->setPosition(center);
}
其中path是一个 std::vector<Vec2> ,用来盛放曲线需要传过的点,10可以理解为曲线的圆滑程度,brick.jpg是你要拉伸的原图,作者从网上扒来的图分享给大家
要注意图片的像素长和宽要是2的倍数,不然会报错 按着上面的例子做,你可能会发现曲线并没有穿越你想要的点,这是因为锚点的问题,我们将曲线位置和锚点重新设置一下就好了: _touchLine->setPosition(Vec2(0,0));
_touchLine->setAnchorPoint(Vec2(0,0));
就像这样,就可以用世界坐标直接去生成曲线了。 virtual void draw(cocos2d::Renderer *renderer,const cocos2d::Mat4 &transform,uint32_t flags);
void onDraw(const cocos2d::Mat4 &transform,bool transformUpdated);
cocos2d::CustomCommand _customCommand;
//上面的是cocos2dx 3.x重写draw的相关声明
bool _makeLine; //判断是否在画线的状态
std::vector<Vec2> _pointArray; //装选择到的字母sprite的坐标
Vec2 _touchPoint; //你当前touch的坐标
TexturedSpline* _touchLine; //那根曲线
void addLinePoint(Vec2 point); //加入选择到的字母的坐标
void deletePoint(); //删除选择到的字母的坐标
void removeTouchLine(); //删除曲线
cpp文件: void GameScene::addLinePoint(Vec2 point)
{
//由于绘制曲线的path不能小于四个点,所以当第一次点击时,往里面先塞三个相同的点
if (_pointArray.size() < 4) {
_pointArray.push_back(point);
_pointArray.push_back(point);
_pointArray.push_back(point);
}
_pointArray.push_back(point);
_makeLine = true;
}
void GameScene::deletePoint()
{
_pointArray.pop_back();
if (_pointArray.size() < 4) {
_makeLine = false;
}
}
void GameScene::removeTouchLine()
{
_pointArray.clear();
_makeLine = false;
}
void GameScene::draw(cocos2d::Renderer *renderer,uint32_t flags)
{
_customCommand.init(zOrderLetters);
_customCommand.func = CC_CALLBACK_0(GameScene::onDraw,this,transform,flags);
renderer->addCommand(&_customCommand);
}
void GameScene::onDraw(const cocos2d::Mat4 &transform,bool transformUpdated)
{
Director *director = Director::getInstance();
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW,transform);
if (_touchLine != NULL) {
this->removeChild(_touchLine);
_touchLine = NULL;
}
if (_makeLine) {
std::vector<Vec2> path;
path.insert(path.end(),_pointArray.begin(),_pointArray.end());
path.push_back(_touchPoint);
//思路是这样的,每次绘制曲线的路径是各个被选中字母的坐标 + 你当前触控的坐标
_touchLine = TexturedSpline::create(path,50,"line.png");
this->addChild(_touchLine,2);
_touchLine->setPosition(Vec2(0,0));
}
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
用法是: 作者刚玩cocos2dx和c++半个月,肯定有写得不周全的地方,如果您有更好的想法请多与我交流 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
