游戏中经常会用到一些变换:
游戏中武器和角色在一个layer上,为了效率,会考虑将bullet, effect和 PhysicsParticle分别放到不用的层上,对应的层上使用batchnode来提高效率
武器和PhysicsParticleLauncher(粒子发射器)绑定,发射的时候,会向PhysicsParticleLayer的武器相同的位置上生成一个物理粒子特效
会经常用到convertToNodeSpace和convertToWorldSpace转换坐标
我们加三个sprite,r0,r1,r2,
r0的父节点是layer, 父节点下坐标(0,0,100,100)
r1的父节点是r0,父节点下坐标(0,0,100,100)
r2的父节点是r1,父节点下坐标(0,0,100,20)
[cpp] view plain copy
- bool HelloWorld::init()
- {
-
-
- if ( !Layer::init() ) {
- return false;
- }
-
-
- Sprite* r0 = Sprite::create("data/pic/gun.png");
- r0->setAnchorPoint(Point(0.f, 0.f));
- this->addChild(r0);
-
-
- Sprite* r1 = Sprite::create("data/pic/gun.png");
- r1->setAnchorPoint(Point(0.f, 0.f));
- r1->setPosition(Point(100, 0));
- r0->addChild(r1);
-
-
- Sprite* r2 = Sprite::create("data/pic/gun.png");
- r2->setAnchorPoint(Point(0.f, 0.f));
- r2->setPosition(Point(100, 20));
- r1->addChild(r2);
-
- }
如何将r2的坐标转换为世界坐标?
如何将r2的坐标转换为r0的局部坐标?
[cpp] view plain copy
-
-
- Point p2world = r2->convertToWorldSpace(Point(0, 0));
-
-
- p2world = r1->convertToWorldSpace(r2->getPosition());
-
-
-
- Point pt = r0->convertToNodeSpace(p2world);
方法如上:
工作原理详见cocos2dx代码
[cpp] view plain copy
- Point Node::convertToWorldSpace(const Point& nodePoint) const
- {
- kmMat4 tmp = getNodeToWorldTransform();
- kmVec3 vec3 = {nodePoint.x, nodePoint.y, 0};
- kmVec3 ret;
- kmVec3Transform(&ret, &vec3, &tmp);
- return Point(ret.x, ret.y);
-
- }
-
- kmMat4 Node::getNodeToWorldTransform() const
- {
- kmMat4 t = this->getNodeToParentTransform();
-
- for (Node *p = _parent; p != nullptr; p = p->getParent())
- kmMat4Multiply(&t, &p->getNodeToParentTransform(), &t);
-
- return t;
- }
cocos2d-x 坐标系详解:http://www.tairan.com/archives/3367
【cocos2dx游戏开发】之坐标系(一) 点击这里