convertToWorldSpace用于将一个相对坐标转化为绝对坐标,convertToNodeSpace则是将一个绝对坐标转化为一个相对坐标。
这里的相对坐标指的是相对于某一个CCNode的坐标(CCNode左下角为0,向右向上为正),这里的绝对坐标是相对于屏幕的坐标(屏幕左下角为0,向右向上为正)。
源码
// 把世界坐标转换到当前节点的本地坐标系中
Vec2 Node::convertToNodeSpace(const Vec2& worldPoint) const
{
Mat4 tmp = getWorldToNodeTransform();
Vec3 vec3(worldPoint.x, worldPoint.y, 0);
Vec3 ret;
tmp.transformPoint(vec3,&ret);
return Vec2(ret.x, ret.y);
}
// 把基于当前节点的本地坐标系下的坐标转换到世界坐标系中
Vec2 Node::convertToWorldSpace(const Vec2& nodePoint) const
{
Mat4 tmp = getNodeToWorldTransform();
Vec3 vec3(nodePoint.x, nodePoint.y, 0);
Vec3 ret;
tmp.transformPoint(vec3,&ret);
return Vec2(ret.x, ret.y);
}
Vec2 Node::convertToNodeSpace(const Vec2& worldPoint) const
{
static Mat4 mat;
mat.setIdentity();
auto parent = getParent();
if (parent)
{
mat = parent->getWorldToNodeTransform() * _attachBone->getWorldMat() * Node::getNodeToParentTransform();
}
else
{
mat = _attachBone->getWorldMat() * Node::getNodeToParentTransform();
}
return mat;
}
从a点移动到b点
void Test::doAnim()
{
//这里必须是世界坐标
Vec2 posWorld = mapWidget["txtCoin"]->getWorldPosition();
//控件txtCoin与控件nodeImg在同一个坐标系下的位置
Vec2 pos = mapWidget["nodeImg"]->getParent()->convertToNodeSpace(posWorld);
mapWidget["nodeImg"]->runAction(Sequence::create(MoveTo::create(0.75, pos), CallFunc::create([&](){
}), NULL));
}