2016-02-29 52 views
2

我正在製作一個遊戲,當主精靈/玩家不斷移動時,他/她需要跳過障礙。速度恆定,同時還能衝動

我需要幫助我如何爲我的移動精靈設置恆定的速度。當我嘗試在SpriteKit更新功能中執行此操作時,無論用戶何時點擊屏幕,我都無法應用衝動。

這是我的代碼。我評論,其中我有麻煩的地方:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    /* Called when a touch begins */ 
    if (gameStarted == false) { 
     gameStarted = true 

     mainSprite.physicsBody?.affectedByGravity = true 
     mainSprite.physicsBody?.allowsRotation = true 
     let spawn = SKAction.runBlock({ 
      () in 

      self.createWalls() 
     }) 


     let delay = SKAction.waitForDuration(1.5) 

     let spawnDelay = SKAction.sequence([spawn, delay]) 

     let spawnDelayForever = SKAction.repeatActionForever(spawnDelay) 

     self.runAction(spawnDelayForever) 

     let distance = CGFloat(self.frame.height + wallPair.frame.height) 

     let movePipes = SKAction.moveByX(0, y: -distance - 50, duration: NSTimeInterval(0.009 * distance)) // Speed up pipes 

     let removePipes = SKAction.removeFromParent() 

     moveAndRemove = SKAction.sequence([movePipes, removePipes]) 

    } else { 
     if died == true { 

     } 
     else { 
      mainSprite.physicsBody?.applyImpulse(CGVectorMake(0, 20)) // TRYING TO APPLY AN IMPULSE TO MY SPRITE SO IT CAN JUMP AS IT MOVES 
     } 
    } 



    for touch in touches { 
     let location = touch.locationInNode(self) 
    } 
} 

override func update(currentTime: CFTimeInterval) { 
    /* Called before each frame is rendered */ 
    updateSpritePosition() 
    mainSprite.physicsBody?.velocity = CGVectorMake(400, 0) // SETS A CONSTANT VELOCITY, HOWEVER I CAN NOT APPLY AN IMPULSE. 
} 

回答

2

的問題是,你是覆蓋在update方法的速度。所以,即使你添加了衝動,它會立即被update中的代碼覆蓋。嘗試覆蓋速度的dx部分。

override func update(currentTime: CFTimeInterval) { 

    updateSpritePosition() 
    mainSprite.physicsBody?.velocity = CGVectorMake(400, mainSprite.physicsBody?.velocity.dy) 
} 
+0

非常感謝! :D <3 – DevelUpGames

+0

沒問題! :) – RaffAl