cocos2dx 坐标之convertToNodeSpace、convertToWorldSpace、convertToNodeSpaceAR、convertToWorldSpaceAR区别和用法

前端之家收集整理的这篇文章主要介绍了cocos2dx 坐标之convertToNodeSpace、convertToWorldSpace、convertToNodeSpaceAR、convertToWorldSpaceAR区别和用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近在看源码的时候,看到这样的几个进行坐标系转换的函数。convertToNodeSpace、convertToWorldSpace、convertToNodeSpaceAR、convertToWorldSpaceAR,在他们的下一层看到下面的注释:

 /**
     * Converts a Point to node (local) space coordinates. The result is in Points.
     */
    Point convertToNodeSpace(const Point& worldPoint) const;

    /**
     * Converts a Point to world space coordinates. The result is in Points.
     */
    Point convertToWorldSpace(const Point& nodePoint) const;

    /**
     * Converts a Point to node (local) space coordinates. The result is in Points.
     * treating the returned/received node point as anchor relative.
     */
    Point convertToNodeSpaceAR(const Point& worldPoint) const;

    /**
     * Converts a local Point to world space coordinates.The result is in Points.
     * treating the returned/received node point as anchor relative.
     */
    Point convertToWorldSpaceAR(const Point& nodePoint) const;

    /**
     * convenience methods which take a Touch instead of Point
     */
    Point convertTouchToNodeSpace(Touch * touch) const;

    /**
     * converts a Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative).
     */
    Point convertTouchToNodeSpaceAR(Touch * touch) const;

具体的解释注释说的很清楚(有个强大的功能叫翻译软件 。。)。

convertToNodeSpace、convertToWorldSpace,都是以参照物的坐下角作为坐标点原点,向右和向上创建坐标系。

------------------------------convertToNodeSpace,获得的坐标相对于参照物的坐标。

------------------------------convertToWorldSpace,获得的坐标是参照物所在的坐标系中的坐标,即转换到参照物的世界坐标。

convertToNodeSpaceAR、convertToWorldSpaceAR,是以参照物的锚点为原点,向右、向上创建坐标系。

------------------------------convertToNodeSpaceAR,获得的坐标相对于参照物的坐标(此时坐标系的原点在参照物的锚点)。

------------------------------convertToWorldSpaceAR,获得的坐标是参照物所在的坐标系中的坐标,即转换到参照物的世界坐标(此时坐标系的原点在参照物的锚点)。

这样理解比较简单写,有AR的是以参照做的锚点作为新建坐标系的原点,没有AR的是以参照物的左下角作为新建坐标系的原点。

下面的示例来验证:

Sprite *sprite1 = Sprite::create("CloseNormal.png");
sprite1->setPosition(Point(100,100));
this->addChild(sprite1);

Sprite *sprite2 = Sprite::create("CloseNormal.png");
sprite2->setPosition(Point(200,200));
this->addChild(sprite2);

auto point1 = sprite1->convertToNodeSpace(sprite2->getPosition());
auto point2 = sprite1->convertToWorldSpace(sprite2->getPosition());
auto point3 = sprite1->convertToNodeSpaceAR(sprite2->getPosition());
auto point4 = sprite1->convertToWorldSpaceAR(sprite2->getPosition());
log("position = (%f,%f)",point1.x,point1.y);
log("position = (%f,point2.x,point2.y);
log("position = (%f,point3.x,point3.y);
log("position = (%f,point4.x,point4.y);


输出的结果:

position = (120.000000,120.000000)
position = (280.000000,280.000000)
position = (100.000000,100.000000)
position = (300.000000,300.000000)

可以通过更改sprite1和sprite2的锚点来验证自己的结果。

猜你在找的Cocos2d-x相关文章