2017-04-11 69 views
2

我正在創建一個精靈遊戲套件,我對swift很陌生。我想要兩個按鈕讓玩家向右或向左移動。當按下按鈕時,說出左邊的按鈕,精靈必須開始向左移動而不停止。當它碰到左側牆時,它會改變方向並向另一側牆移動,等等......我設法讓精靈通過使用更新功能來做到這一點。每次調用它都會檢查玩家是否正在按下一個按鈕,並且會相應地移動該小精靈,但是,它會導致某種FPS滯後(FPS將下降到50)。如何移動精靈而不會導致fps滯後

我嘗試使用MoveBy和MoveTo等SKActions,但無法重新創建我想要的精靈。

所以我的問題是:我如何使精靈按照我想要的方式移動使用兩個按鈕,而不會導致FPS滯後。任何幫助,將不勝感激。謝謝

這裏是我在更新函數中調用的函數,但是造成了滯後。

func moveRight() { 
    sprite.xScale = 1 
    sprite.position.x += 4 
} 

func moveLeft() { 
    sprite.xScale = -1 
    sprite.position.x -= 4 
} 
+0

顯然,這樣的事情是不會引起滯後,如果你想獲得真正的答案,而不是從人猜測這裏https://stackoverflow.com/help/mcve看一看。 – Knight0fDragon

回答

2

試試這個代碼:

它運行永遠當按鈕被按下的移動動作和釋放按鈕時,它消除了行動

這將讓玩家不失幀希望移動率。要改變精靈在撞擊牆壁時的方向,你必須檢查碰撞。當它碰到牆壁時,您可以檢查它是否是正在應用的leftMove或RightMove操作,然後移除該操作並啓動相反的操作。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

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

     if(leftButton.contains(location) { // check if left button was pressed 
      moveLeft() 
     } else if(rightButton.contains(location) { //check if right button was pressed 
      moveRight() 
     } 
    } 
} 

func moveLeft() { 
    //Check if it's already moving left, if it is return out of function 
    if((sprite.action(forKey: "leftMove")) != nil) { 
     return 
    } 
    //Check if its moving right, if it is remove the action 
    if((sprite.action(forKey: "rightMove")) != nil) { 
     sprite.removeAllActions() 
    } 
    //Create and run the left movement action 
    let action = SKAction.move(by: -100, duration: 1) 
    sprite.run(SKAction.repeatForever(action), withKey: "leftMove") 
} 

func moveRight() { 
    //Check if it's already moving right, if it is return out of function 
    if((sprite.action(forKey: "rightMove")) != nil) { 
     return 
    } 
    //Check if its moving left, if it is remove the action 
    if((sprite.action(forKey: "leftMove")) != nil) { 
     sprite.removeAllActions() 
    } 
    //Create and run the right movement action 
    let action = SKAction.move(by: 100, duration: 1) 
    sprite.run(SKAction.repeatForever(action), withKey: "rightMove") 
} 
+0

移動函數被調用,但精靈不移動...什麼可能是錯的? – RT5754

+0

好的,價值的舉動可能真的很低,這使得它看起來不動。嘗試將0.4改爲像1000這樣愚蠢的東西,看看它是否會移動。還要確保你想要移動的精靈正在調用運行動作。 –

+0

好吧,這是問題的一部分,我改變了價值更大。當我按下按鈕時,它現在會移動。當我釋放時它繼續移動(這是正確的),但之後當我按下按鈕後它不移動,它只是移動一點點 - 按鈕方向的相反方向。我不知道發生了什麼 – RT5754