如何在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;
    }
}}

提前感谢!

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

@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;
}

我找到的唯一解决方案是将节点固定在特定位置。

但是想知道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];}

最新更新