2014-02-22 38 views
3

我正在關注SpriteKit教程here,以創建一個簡單的精靈套件射擊遊戲,您可以製作一艘太空飛船,在小行星上發射激光。SKAction moveTo應該降低

我想讓激光(每個激光是一個SKSpriteNode)移動到點擊的位置。我在方法touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event內正確地獲取了觸摸。然而,當我在SKSpriteNode上設置一個SKAction時,它會在y方向的OPPOSITE上移動,我點擊它。即圖像窗口的寬度(x)500和高度(y)400.當我觸摸屏幕的座標(300,100)時,lazer似乎移動到座標(300,300)。

我驗證了touchLocation中的座標是正確的。

僅供參考我只使用iPhone模擬器 - 但這應該不重要,應該嗎?

相關的代碼片段:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    SKSpriteNode *shipLaser = [_shipLasers objectAtIndex:_nextShipLaser]; 

    shipLaser.position = CGPointMake(_ship.position.x+shipLaser.size.width,_ship.position.y+0); 
    shipLaser.hidden = NO; 
    [shipLaser removeAllActions]; 

    UITouch *touch = [touches anyObject]; 
    CGPoint touchLocation = [touch locationInView:self.view]; 

    SKAction *laserMoveAction = [SKAction moveTo:touchLocation duration:0.5]; 
    SKAction *laserDoneAction = [SKAction runBlock:(dispatch_block_t)^() { 
     shipLaser.hidden = YES; 
    }]; 

    SKAction *moveLaserActionWithDone = [SKAction sequence:@[laserMoveAction,laserDoneAction]]; 
    [shipLaser runAction:moveLaserActionWithDone withKey:@"laserFired"]; 
} 

編輯:我不知道是否有可能與事實SprikeKit的座標系統從底部來源於剩下的事情,而UIKit中從左上角的起源?

+0

爲什麼'_ship.position.y + 0'?另外,shipLaser的父母是什麼? – prototypical

+0

'+ 0'並不重要,它是從教程中複製粘貼代碼的結果。 'shipLaser'的父級是視圖控制器 - 在init_方法內,我在'_shipLasers'數組中的每個對象上調用'[self addChild:shipLaser]' –

+0

您是不是將激光添加到SKScene? – prototypical

回答

4

你想要SKScene中的touchLocation,而不是UIView。

變化:

CGPoint touchLocation = [touch locationInView:self.view]; 

到:

CGPoint touchLocation = [touch locationInNode:self]; 
+0

非常感謝,這是訣竅! :)這是我的問題的正確答案,但我將在下面留下我以前的解決方案,以解釋爲什麼您需要在SKScene中觸摸的位置,而不是視圖。 –

1

的問題是,SprikeKit的座標系統來源於左下角,不像UIKit中的座標系統,它起源於右上角。所以touch事件的座標位於UIkit的座標系統中,而SKNode正在SpriteKit的系統中移動。一旦我理解了這種差異,就很容易解決。

+0

我建議你只使用SKScene座標系。你沒有理由是什麼? – prototypical

+0

直到你建議它,我才意識到這種方法,你的解決方案是正確的。 –

+0

如果您使用的教程使用'locationInView',我會感到驚訝。只是好奇你爲什麼會選擇這樣做。你習慣於使用UIKit嗎? – prototypical