2016-02-29 56 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