2016-07-26 5 views
1

Ich bin Anfänger in Swift und ich brauche deine Tipps und Hilfe. Ich habe SKTextureNode mit Textur und ich habe 5 Koordinaten (Positionen).Spawn Knoten nach dem Zufallsprinzip

Ich versuche zu verstehen, wie man eine SKSpriteNode zwischen 5 Positionen zufällig mit Zeitintervall in Swift spawn.

Zum Beispiel:

let coordinate1 = CGPoint (x: my coordinates, y: my coordinates) let coordinate2 = .....

Ich versuche, meine Textur an diesen Punkten, um zu laichen, aber ich weiß nicht, wie ich das tun kann. Ich weiß, wie ich Aktionen für meine Knoten hinzufügen kann. Ich möchte, dass sie nach Laich zum Laichen und fallen ...

Antwort

1
class GameScene: SKScene { 
    var positions: [CGPoint]! = [CGPoint]() 
    var myHero: SKSpriteNode! 
    override func didMoveToView(view: SKView) { 
     let pos1 = CGPointMake(50,400) 
     positions.append(pos1) 
     let pos2 = CGPointMake(100,400) 
     positions.append(pos2) 
     let pos3 = CGPointMake(200,400) 
     positions.append(pos3) 
     let pos4 = CGPointMake(300,400) 
     positions.append(pos4) 
     let pos5 = CGPointMake(400,400) 
     positions.append(pos5) 
     //... or : positions = [pos1,pos2,pos3...] 
     self.myHero = SKSpriteNode.init(color: SKColor.blueColor(), size: CGSizeMake(50,50)) 
     self.myHero.alpha = 0.0 
     addChild(self.myHero) 
     spawn(15) 
    } 
    func spawn(count:Int) { 
     let generateRandom = SKAction.runBlock({ 
      let randomPosNum = randomNumber(0...self.positions.count-1) 
      let randomTime = randomDouble(1.0, max: 3.0) 
      print("randomPos: \(randomPosNum) exit in randomTime:\(randomTime) ") 
      self.myHero.position = self.positions[randomPosNum] 
      self.runAction(SKAction.waitForDuration(randomTime)) 
     }) 
     let fadeIn = SKAction.fadeInWithDuration(0.5) 
     let fadeOut = SKAction.fadeOutWithDuration(0.0) 
     let fall = SKAction.moveToY(-30, duration: 0.5) 
     self.myHero.runAction(SKAction.repeatAction(SKAction.sequence([generateRandom,fadeIn,fall,fadeOut]), count: count)) 
    } 
} 
func randomNumber(range: Range<Int> = 1...6) -> Int { 
    let min = range.startIndex 
    let max = range.endIndex 
    return Int(arc4random_uniform(UInt32(max - min))) + min 
} 
func randomDouble(min: Double, max: Double) -> Double { 
    return (Double(arc4random())/Double(UINT32_MAX)) * (max - min) + min 
} 

Ausgang:

enter image description here

+1

Vielen Dank! –