2014-03-26 26 views
1

我怎样才能在这个例子中_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); 

提前许多感谢, 伊恩

回答

2

你的代码有很多错误。

_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-

看在代码两个NSLogs:

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将转换(10,10)的_childNode到_worldNode,使得它(20,20 )。

尝试使用该行:

CGPoint position = [self convertPoint:_childNode.position fromNode:_worldNode]; 
NSLog (@"Position: %@", [NSValue valueWithCGPoint:position]); 

这会给你w.r.t现场,这是你在瞄准了什么位置。

+1

非常感谢!实际上,对于我所做的事情,这很好,尽管我很欣赏它让我感到困惑,我为此感到遗憾。再次,快速的例子,愚蠢的错误,忘记了它拉德拉斯。 3.解决方案有效,这是一个愚蠢的错误,我认为点位已隐式转换(?)。 – Ian

1

简而言之:旋转不会改变节点的位置。

SKSpriteNodeposition返回该节点的位置anchorPoint

当您旋转SKSpriteNode时,它旋转了其anchorPoint,因此节点的anchorPoint保持与旋转前相同的位置。这就是为什么你总是得到(10,10)