2017-04-02 48 views
0

我正在學習一些SpriteKit。我試圖做到這一點:在水龍頭移動節點右 - >在右牆碰撞翻轉節點的紋理 - >改變方向,並重復,如果在左牆上。在碰撞後翻轉SKSpriteNode紋理使其循環

問題是,碰撞後它將循環圖像翻轉。什麼會造成這種情況?

我移動SKSPriteNode觸摸:

moveAction = SKAction.moveBy(x: 100, y: 0, duration: 1) 
node.run(moveAction, withKey: "Right") 
node.physicsBody?.velocity = CGVector(dx: 0, dy: 0) 
node.physicsBody?.applyImpulse(CGVector(dx: 40, dy: 130)) 

這是我如何檢測碰撞:

if (firstBody.categoryBitMask & PhysicsCatagory.node == PhysicsCatagory.node && 
      secondBody.categoryBitMask & PhysicsCatagory.RightWall == PhysicsCatagory.RightWall) { 

      direction = "Left" 
      rotate() 
     }else if (firstBody.categoryBitMask & PhysicsCatagory.RightWall == PhysicsCatagory.RightWall && 
      secondBody.categoryBitMask & PhysicsCatagory.node == PhysicsCatagory.node) { 

      direction = "Left" 
      rotate() 
     } 

而且這樣我翻轉節點:

func rotate(){ 
     if direction == "Right"{ 
      node.xScale = node.xScale * -1 
      updateScoreAndChangeBackgroundColor() 
     }else{ 
      node.xScale = node.xScale * -1 
      updateScoreAndChangeBackgroundColor() 
     } 
    } 

我明白只要方向沒有改變,它就會一直髮生碰撞,而我正在點擊它。但是如何並且應該將節點反彈回來以防止這種情況發生?

+0

什麼是 「它會循環圖像翻轉」 是指旋轉? – 0x141E

+0

@ 0x141E它多次執行任務。例如,如果您在碰撞時添加分數,而不是添加分數,則會添加3.只要碰撞停止,它就會添加分數。只要碰撞停止,就會翻轉圖像。 –

+0

也許你可以將'direction'(例如「Left」)傳遞給'rotate'方法,並且只有當參數和當前方向不一樣時,纔會翻轉字符並增加分數,並且在'旋轉「方法。 – 0x141E

回答

1

嘗試......

func rotate(newDirection:String) { 
    if newDirection != direction { 
     node.xScale = node.xScale * -1 
     updateScoreAndChangeBackgroundColor() 
     direction = newDirection 
    } 
} 

,並呼籲與

rotate (newDirection: "Left") 

或本

rotate (newDirection: "Right") 
+0

沒辦法。它確實有效。非常感謝 :) –