如何在Sprite Kit上触及节点中心位置?

时间:2014-05-05 11:33:06

标签: position sprite-kit

我在Xcode中使用Sprite Kit并且位置有问题。

我想拖动节点并拖放到目标区域。如果不是正确的目标,则将节点发送回旧位置。

我的代码工作但是当我触摸节点(节点的中心除外)时,任何地方都会保持旧位置的中心点。因此,如果目标错误,由于触摸点而移动的节点不同于中心点节点

因此,如果我能够获得触摸节点的中心位置,那么我可以以绝对位置发回!

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];    
[self selectNodeForTouch:positionInScene];}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPoint previousPosition = [touch previousLocationInNode:self];
CGPoint translation = CGPointMake(positionInScene.x - previousPosition.x, positionInScene.y - previousPosition.y);
[self panForTranslation:translation];

}

//

-(void)selectNodeForTouch:(CGPoint)touchLocation{

SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint: touchLocation];

if (![_selectedNode isEqual:touchedNode.name]) {
    _selectedNode =touchedNode;

      if ((newPositionStone.x-28)<5 || (newPositionStone.x-28)>(5*(-1))){
        NSLog(@"Great! you drop node to target ");
    }
    else{
        NSLog(@"Didn't drop node to target");//Send back to old position
        _selectedNode.position = oldPositionStone;
    }
}}

提前致谢!

2 个答案:

答案 0 :(得分:0)

您需要在触摸时存储对象的位置,以便在拖动目标失败时可以恢复为该位置。

@implementation中创建一个CGPoint变量,如下所示:

@implementation MyScene
{
    CGPoint objectStartPosition;
}

touchesBegan:设置对象的当前位置:

objectStartPosition = newPositionStone.position;

然后在touchesEnded:检查节点的目的地是否有效:

if(whatever x and y positions you need to check for in here)
{
    // do whatever you need to
} else {
    newPositionStone.position = objectStartPosition;
}

答案 1 :(得分:0)

我创建的唯一解决方案,将节点固定在特定位置。

但是想知道Sprite Kit有找到触摸节点位置的方法吗?

这是我的解决方案

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];

if (positionInScene.x>400.0 && positionInScene.x<430.0) {
    //Fix the position to original
    oldPositionStone.x = 414;
    oldPositionStone.y = 25;
}

[self selectNodeForTouch:positionInScene];}

//比

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];

NSLog(@"Touches END %f %f",positionInScene.x,positionInScene.y);
if (positionInScene.x>15 && positionInScene.x<40) {
    newPositionStone.x=28;
    newPositionStone.y = 25;
    if ([_selectedNode.name isEqualToString:@"stone"]) {
        _selectedNode.position=newPositionStone;
    }

}
else{
    positionInScene  = oldPositionStone;
    _selectedNode.position = positionInScene;
}
[self selectNodeForTouch:positionInScene];}