[英]Sprite Kit: Getting the absolute node position
如何在此示例中获取_childNode的绝对位置:
我有一个父母:_worldNode
我有一个孩子:_childNode
我将_childNode位置设置为10,10。
我将_worldNode旋转90度。
现在,当我查询_childNode位置时,我得到10,10。 当然不再是这种情况。 甚至做[_childNode calculateAccumulatedFrame]在10,10给我一个CGRect。
任何想法如何返回正确的位置(-10,10)? 这是我测试的代码(只需放入init,所有日志返回10,10)。
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGPoint screenCentre = CGPointMake(screenHeight/2.0,screenWidth/2.0);
_worldNode = [SKNode node];
_worldNode.position = screenCentre;
[self addChild:_worldNode];
_childNode = [[SKSpriteNode alloc] initWithColor:[UIColor redColor] size:CGSizeMake(10, 10)];
_childNode.position = CGPointMake(10, 10);
[_worldNode addChild:_childNode];
NSLog(@"position of child pre rotation %f, %f", _childNode.position.x, _childNode.position.y);
_worldNode.zRotation = 90;
NSLog(@"position of child after rotation %f, %f", _childNode.position.x, _childNode.position.y);
CGPoint position = _childNode.position;
[_childNode convertPoint:position toNode:_worldNode];
NSLog(@"position of child after conversion %f, %f", position.x, position.y);
CGRect groupRect = [_childNode calculateAccumulatedFrame];
CGPoint newPosition = CGPointMake(groupRect.origin.x + (groupRect.size.width / 2), groupRect.origin.y + (groupRect.size.height / 2));
NSLog(@"position of child based on frame %f, %f",newPosition.x,newPosition.y);
非常感谢,伊恩
您的代码中存在很多错误。
1-
_worldNode.position = screenCentre; //This places the node at the SKScene centre
应该
_worldNode.position = CGPointZero; //This places the node at the origin.
SKScene的默认坐标系的原点位于左下角。
2-
_worldNode.zRotation = 90;
应该
_worldNode.zRotation = M_PI_2;
zRotation以弧度而非度数来度量。
3-
查看代码中的两个NSLog:
NSLog(@"position of child after rotation %f, %f", _childNode.position.x, _childNode.position.y); // - 1
CGPoint position = _childNode.position;
[_childNode convertPoint:position toNode:_worldNode]; //returns a CGPoint, where are you storing it?
NSLog(@"position of child after conversion %f, %f", position.x, position.y); // - 2
position
变量实际上没有转换。 该方法返回另一个CGPoint,而后者又需要记录。
但是,这将返回错误的位置,因为_childNode.position
存储它相对于它的父级(即_worldNode
)的位置,因此使用convertPoint
到_worldNode
会将_childNode上的(10,10)转换为_worldNode,使其成为(20,20)。
请尝试使用此行:
CGPoint position = [self convertPoint:_childNode.position fromNode:_worldNode];
NSLog (@"Position: %@", [NSValue valueWithCGPoint:position]);
这将为您提供场景的位置,这就是您的目标。
简而言之:旋转不会改变节点的位置。
SKSpriteNode
的position
返回该节点的anchorPoint
位置。
旋转SKSpriteNode
,它会在其anchorPoint
上旋转,因此节点的anchorPoint
保持与旋转前相同的位置。 这就是你总能得到的原因(10,10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.