学习视差节点的心得

之前想要实现关于视差的效果,一直都是想自己写代码,今天偶然看见了关于视差节点的文章,觉得很有用必须学习一下!

首先视差节点的类型名称是ParallaxNode,创建方法很简单:

this->pn = ParallaxNode::create();

创建完成之后,需要往里面添加精灵节点,我再这里创建两个精灵节点

auto background = Sprite::create("HelloWorld.png");
background->setAnchorPoint(Vec2(0, 0));
background->setPosition(Vec2(0, 0));

auto grass = Sprite::create("grass.png");
grass->setAnchorPoint(Vec2(0, 0));
grass->setPosition(0, 0); 

由于需要产生视差效果,所以我们需要把这两个精灵添加到这个ParallaxNode里面:

this->pn->addChild(background, -1, Vec2(1.0f, 1.2f), Vec2::ZERO);
this->pn->addChild(grass, 1, Vec2(2.0f, 2.4f), Vec2::ZERO);

需要说明的是addChild里面的各个参数的作用:

(1)不用说了吧

(2)ZOrder即排列顺序

(3)在XY轴上相对于pn的移动比例

(4)在pn里面的相对位置

而文档里面是这样描述addChild()的:

void addChild (Node *child, int z, const Vec2 &parallaxRatio, const Vec2 &positionOffset) 

添加完成之后,我们需要对pn进行移动,当我们移动pn的时候,内部的两个精灵也会进行移动,但其移动的幅度会根据上述的第三个参数而指定。

我们一般使用update(float delta)来指定移动速度。

当然我们也必须要在onEnter()函数中添加scheduleUpdate()函数来启动schedule。

其中update(float delta)中的内容是:

auto x = this->pn->getPositionX() - 1;
pn->setPositionX(x);

 

posted @ 2015-07-01 10:16  FERRYSELING  阅读(207)  评论(0编辑  收藏  举报