2014-06-20 61 views
0

我嘗試創建一個應用程序,當觸摸開始時創建一個精靈節點,當用戶的手指移動時拖動它,當觸摸結束時拖動它。我現在有簡單的創建新的觸摸位置的新精靈:在Sprite Kit中從頭到尾攜帶一個觸摸事件

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

    SKSpriteNode *gamePiece = [self pickObject]; 
    gamePiece.position = location; 
    gamePiece.physicsBody.dynamic = NO; 

    [self addChild:gamePiece]; 


} 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
/* Called when a touch begins */ 

for (UITouch *touch in touches) { 
    CGPoint location = [touch locationInNode:self]; 

    SKSpriteNode *gamePiece = [self pickObject]; 
    gamePiece.position = location; 
    gamePiece.physicsBody.dynamic = NO; 

    [self addChild:gamePiece]; 


} 


} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
/* Called when a touch begins */ 

for (UITouch *touch in touches) { 
    CGPoint location = [touch locationInNode:self]; 

    SKSpriteNode *gamePiece = [self pickObject]; 
    gamePiece.position = location; 
    gamePiece.physicsBody.dynamic = NO; 

    [self addChild:gamePiece]; 


} 


} 

如何執行跨觸摸方法相同,單一的精靈節點?我已經搜索了很多教程,但似乎沒有什麼符合我需要的東西。

回答

0

您可以通過維護觸摸的實例變量以及與該觸摸關聯的SKSpriteNode來完成此操作。

@implementation MyScene 
{ 

UITouch *currentTouch; 
SKSpriteNode *currentGamePiece; 

} 

然後,修改觸摸代表如下:

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

     SKSpriteNode *gamePiece = [self pickObject]; 
     gamePiece.position = location; 
     gamePiece.physicsBody.dynamic = NO; 

     [self addChild:gamePiece]; 

     currentTouch = touch; 
     currentGamePiece = gamePiece; 


    } 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    /* Called when a touch begins */ 

    for (UITouch *touch in touches) { 
     CGPoint location = [touch locationInNode:self]; 

     if ([touch isEqual:currentTouch]) 
     { 
      currentGamePiece.position = location; 
     } 

    } 

} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    /* Called when a touch begins */ 

    for (UITouch *touch in touches) 
    { 
     CGPoint location = [touch locationInNode:self]; 

     if ([touch isEqual:currentTouch]) 
     { 
      currentGamePiece.position = location; 
      currentGamePiece = nil; 
      currentTouch = nil; 

     } 

} 
+0

工作就像一個魅力。謝謝! – cocoamoco