2016-05-29 21 views
0

我在我的swift項目中擁有以下精靈套件場景。它會在屏幕上移動一個SKNode。問題是我希望圓圈可以向上和向下移動,但它只能向下或向下移動。我檢查了yMove的值,以確認它在y軸上隨機生成正向變化。它正在生成這些正值,但該對象仍然只能水平和垂直移動。獲取精靈套件對象向上移動

class GameScene: SKScene { 


override func didMoveToView(view: SKView) { 
    backgroundColor = SKColor.whiteColor() 

    runAction(SKAction.repeatActionForever(
     SKAction.sequence([ 
      SKAction.runBlock(addKugel), 
      SKAction.waitForDuration(1.0) 
      ]) 
     )) 


} 

func addKugel() { 

    // Create sprite 
    let kugel = SKShapeNode(circleOfRadius: 100) 
    kugel.strokeColor = SKColor.blackColor() 
    kugel.glowWidth = 1.0 

    // Determine where to spawn the monster along the Y axis 
    let actualY = random(min: 200/2, max: size.height - 200/2) 

    // Position the monster slightly off-screen along the right edge, 
    // and along a random position along the Y axis as calculated above 
    kugel.position = CGPoint(x: size.width + 200/2, y: actualY) 

    // Add the monster to the scene 
    addChild(kugel) 

    // Determine speed of the monster 
    let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0)) 

    //randomly create coefficients for movement 
    let xVector = random(min: CGFloat(0.0), max: CGFloat(1.0)) 
    var yVector = random(min: CGFloat(0.0), max: CGFloat(1.0)) 

    //overly complicated way to make a number negative 50 percent of the time 
    var probNegative = random(min: CGFloat(0.0), max: CGFloat(1.0)) 
    if (probNegative > 0.5){ 
     yVector = 0.0 - yVector 
    } 
    debugPrint(yVector) 
    // Create the actions 
    let yMove = (200/2)*yVector 
    debugPrint(yMove) 
    let actionMove = SKAction.moveTo(CGPoint(x: -200/2*xVector, y: yMove), duration: NSTimeInterval(actualDuration)) 
    let actionMoveDone = SKAction.removeFromParent() 
    kugel.runAction(SKAction.sequence([actionMove, actionMoveDone])) 

} 
} 

回答

0

所以我很誤解moveTo在做什麼。所有moveTo所做的都是將Sprite移動到特定的CGPoint。我按照我的精靈尺寸縮放y座標,而不是隨機選擇0size.height之間的值。 以下是上述代碼片段的簡化版本:

func addKugel() { 
    let KUGELWIDTH = 50.0 

    let kugel = SKShapeNode(circleOfRadius: CGFloat(KUGELWIDTH)/2) 
    kugel.strokeColor = SKColor.blackColor() 
    kugel.glowWidth = 1.0 

    let actualY = random(min: CGFloat(KUGELWIDTH)/2, max: (size.height - CGFloat(KUGELWIDTH)/2)) 
    debugPrint("actualY: \(actualY)") 

    kugel.position = CGPoint(x: size.width + CGFloat(KUGELWIDTH/2), y: actualY) 

    addChild(kugel) 

    let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0)) 

    let y = random(min: CGFloat(0.0), max: CGFloat(1.0)) 
    let yPos = CGFloat(y)*size.height 

    let actionMove = SKAction.moveTo(CGPoint(x: 0.00, y: yPos), duration: NSTimeInterval(actualDuration)) 
    let actionMoveDone = SKAction.removeFromParent() 
    kugel.runAction(SKAction.sequence([actionMove, actionMoveDone])) 

}