2015-09-13 2 views
0

Я пытаюсь включить анимацию из 5 кадров в мою существующую функцию появления для spritenode. В настоящее время ворон перемещается по экрану справа налево, я хотел бы оживить его, но независимо от того, что я пытаюсь, я продолжаю генерировать ошибки Thread 1.Анимация изображения с помощью функции spawn

Прокомментировав некоторые фрагменты кода, я могу либо анимировать птицу в статическом положении на экране, либо переместить птицу справа налево, но не анимировать (комментировать outple func).

Я знаю, что приведенный ниже код не будет работать в текущей форме, но это все, с чем я работаю, надеюсь, кто-то может мне помочь.

Ниже весь мой код, я пытаюсь слот вместе ...

Спасибо,

//did move to view 

var crowTexture1 = SKTexture(imageNamed: "crow1") 
crowTexture1.filteringMode = SKTextureFilteringMode.Nearest 
var crowTexture2 = SKTexture(imageNamed: "crow2") 
crowTexture2.filteringMode = SKTextureFilteringMode.Nearest 
var crowTexture3 = SKTexture(imageNamed: "crow3") 
crowTexture3.filteringMode = SKTextureFilteringMode.Nearest 
var crowTexture4 = SKTexture(imageNamed: "crow4") 
crowTexture4.filteringMode = SKTextureFilteringMode.Nearest 
var crowTexture5 = SKTexture(imageNamed: "crow5") 
crowTexture5.filteringMode = SKTextureFilteringMode.Nearest 


    var animFly = SKAction.animateWithTextures([crowTexture1, crowTexture2, crowTexture3, crowTexture4, crowTexture5], timePerFrame: 0.1) 
    var fly = SKAction.repeatActionForever(animFly) 

    var distanceToMoveBird = CGFloat(self.frame.size.width + 2 * crowTexture1.size().width); 
    var moveBirds = SKAction.moveByX(-distanceToMoveBird, y:0, duration:NSTimeInterval(0.0040 * distanceToMoveBird)); 
    var removeBirds = SKAction.removeFromParent(); 
    moveAndRemoveBirds = SKAction.sequence([moveBirds, removeBirds,]); 

    var spawnBirds = SKAction.runBlock({() in self.spawnBird()}) 
    var delayBirds = SKAction.waitForDuration(NSTimeInterval(4.0)) 
    var spawnThenDelayBirds = SKAction.sequence([spawnBirds, delayBirds]) 
    var spawnThenDelayForeverBirds = SKAction.repeatActionForever(spawnThenDelayBirds) 
    self.runAction(spawnThenDelayForeverBirds) 

//spawning function 

func spawnBird() { 


    var bird = SKSpriteNode() 
    bird.position = CGPointMake(self.frame.size.width + crowTexture1.size().width * 2, 0); 
    var height = UInt32(self.frame.size.height/1) 
    var height_max = UInt32(500) 
    var height_min = UInt32(500) //300 
    var y = arc4random_uniform(height_max - height_min + 1) + height_min; 
    var bird1 = SKSpriteNode(texture: crowTexture1) 



    bird1.position = CGPointMake(0.0, CGFloat(y)) 
    bird1.physicsBody = SKPhysicsBody(rectangleOfSize: bird1.size) 
    bird1.physicsBody?.dynamic = false 
    bird1.physicsBody?.categoryBitMask = crowCategory 
    bird1.physicsBody?.collisionBitMask = catCategory | scoreCategory 
    bird1.physicsBody?.contactTestBitMask = 0 
    bird.addChild(bird1) 

    bird.runAction(moveAndRemoveBirds) 

    birds.addChild(bird) 

} 

ответ

0

Чтобы настроить мой пример для того, чтобы работать (если вы просто скопировать & вставить код) , вам нужен atlas с именем crow.atlas с текстурами под названием [email protected], [email protected] и т. д. Если вы не хотите использовать атлас, вы можете инициализировать текстуры вручную, как вы уже делали (просто положите ваш код внутри initializeCrowAnimation способ).

Я написал все необходимые комментарии внутри кода:

import SpriteKit 

class GameScene: SKScene { 

    let CrowCategory : UInt32 = 0x1 << 1 
    let CatCategory : UInt32 = 0x1 << 2 
    let ScoreCategory : UInt32 = 0x1 << 3 

    var animationFrames : [SKTexture]! 

    override func didMoveToView(view: SKView) { 

     //1 - Get textures 

     initializeCrowAnimation() 

     // 2 - Generate birds 
     generateBirds() 

    } 


    //Initialize crow animation - first way 

    func initializeCrowAnimation(numOfFrames:Int){ 

     //You can use numOfFrames parameter if you want to get only certain number of textures from atlas 

     animationFrames = [SKTexture]() 

     let atlas = SKTextureAtlas(named: "crow") 


     for var i = 1; i <= atlas.textureNames.count; i++ { 

      let textureName = "crowAnimation\(i)" 


      animationFrames.append(atlas.textureNamed(textureName)) 
     } 

    } 

    //Initialize crow animation - second way 

    func initializeCrowAnimation(){ 


     let atlas = SKTextureAtlas(named: "crow") 

     animationFrames = [ 
      atlas.textureNamed("crowAnimation1"), 
      atlas.textureNamed("crowAnimation2"), 
      atlas.textureNamed("crowAnimation3"), 
      atlas.textureNamed("crowAnimation4"), 
      atlas.textureNamed("crowAnimation5"), 
     ] 


    } 

    //Helper methods 

    func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{ 
     return CGFloat(arc4random())/CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum) 
    } 

    func getRandomPoint()->CGPoint{ 

     var xRange:UInt32 = UInt32(frame.size.width) // you can change the range here if you like 
     var yRange:UInt32 = UInt32(frame.size.height) // you can change the range here if you like 

     return CGPoint(x:Int(arc4random()%xRange),y:Int(arc4random()%yRange)) 
    } 


    //Method for creating bird node 

    func getBird()->SKSpriteNode{ 

     let bird = SKSpriteNode(texture: animationFrames.first) 
     bird.physicsBody = SKPhysicsBody(rectangleOfSize: bird.size) 
     bird.physicsBody?.dynamic = false 
     bird.physicsBody?.categoryBitMask = CrowCategory 
     bird.physicsBody?.collisionBitMask = CatCategory | ScoreCategory 
     bird.physicsBody?.contactTestBitMask = 0 
     bird.name = "crow" //will help you to enumerate all crows if needed 

     //Flying animation 
     let flyAnimation = SKAction.repeatActionForever(SKAction.animateWithTextures(animationFrames, timePerFrame: 0.1)) 

     bird.runAction(flyAnimation, withKey: "flying") // you can stop flying animation at any time by removing this key 

     //Moving animation 

     let move = SKAction.moveTo(getRandomPoint(), duration: NSTimeInterval(randomBetweenNumbers(4, secondNum:6))) 

     let remove = SKAction.removeFromParent() 

     let moveAndRemove = SKAction.sequence([move,remove]) 

     bird.runAction(moveAndRemove, withKey: "moving") 


     return bird 

    } 

    //If needed you can use something like this to stop generating birds, or any other action associated by certain key 

    func stopGeneratingBirds(){ 

     if(self.actionForKey("spawning") != nil){ 

      self.removeActionForKey("spawning") 
     } 

    } 

    func generateBirds(){ 

     //spawn a bird with delay between 2 + (+1/-1) means, between 1 and 3 seconds 
     let delay = SKAction.waitForDuration(2, withRange: 1) 


     var block = SKAction.runBlock({ 

      //Note that here if you don't use something like [unowned self] or [weak self] you will create a retain cycle 

      //Because I am using outdated Swift version (and retain cycle is a whole new topic), I will skip it 

      var bird = self.getBird() 

      bird.position = self.getRandomPoint() 

      println(bird.position) 

      self.addChild(bird) 

     }) 



     let spawnSequence = SKAction.sequence([delay, block]) 


     self.runAction(SKAction.repeatActionForever(spawnSequence), withKey: "spawning") 
    } 

    deinit{ 
     println("Deinited") 
    } 

    override func update(currentTime: CFTimeInterval) { 
     /* Called before each frame is rendered */ 
    } 

} 

Заметим, что это только пример, который может дать вам основную идею, в каком направлении вы можете пойти, и сравнить свой код с этим, чтобы увидеть почему ваш код не работает.

Это проверено и работает, но помните, что, возможно, я что-то пропустил.

Об удержании циклов и о том, как их избежать, можно read more here (и обновите свой код соответственно). Я пропустил, чтобы добавить эту часть в свой ответ, потому что моя версия Swift устарела и, вероятно, то, что работает для меня, не сработает для вас, но ключ должен использовать [unowned self] или [weak self]. Такую же тему можно найти в документах here.

+0

спасибо за ваш комментарий, я играл с вашим кодом, и мне нравится концепция, я не могу интегрировать его с моим кодом, где одна птица входит на экран справа налево в определенных пределах высоты , Птица должна пересечь весь экран, поскольку это триггер, увеличивающий счет, как только птица попадает в контакт в левой части экрана ... Если вы или кто-либо еще узнаете, как достичь этого, это то, что я и я был бы очень благодарен. –

Смежные вопросы