Randomizing node movement duration

前端 未结 2 661
清酒与你
清酒与你 2021-01-25 13:09

I am making a game in SpriteKit and I have a node that is moving back and forth across the screen and repeating using the code:

    let moveRight = SKAction.move         


        
相关标签:
2条回答
  • 2021-01-25 13:29

    When you run actions like from your example and randomize duration parameter with something like arc4Random this is actually happening:

    • Random duration is set and stored in action.
    • Then action is reused in a sequence with a given duration.

    Because the action is reused as it is, duration parameter remains the same over time and moving speed is not randomized.

    One way to solve this (which I prefer personally) would be to create a "recursive action", or it is better to say, to create a method to run desired sequence and to call it recursively like this :

    import SpriteKit
    
    class GameScene: SKScene {
    
        let  shape = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 20, height: 20))
    
        override func didMoveToView(view: SKView) {
    
    
           shape.position = CGPointMake(CGRectGetMidX(self.frame) , CGRectGetMidY(self.frame)+60 )
    
           self.addChild(shape)
    
           move()
        }
    
    
        func randomNumber() ->UInt32{
    
            var time = arc4random_uniform(3) + 1
            println(time)
            return time
        }
    
        func move(){
    
            let recursive = SKAction.sequence([
    
                SKAction.moveByX(frame.size.width/2.8, y: 0, duration: NSTimeInterval(randomNumber())),
                SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: NSTimeInterval(randomNumber())),
                SKAction.runBlock({self.move()})])
    
            shape.runAction(recursive, withKey: "move")
        }
    
    }
    

    To stop the action, you remove its key ("move").

    0 讨论(0)
  • 2021-01-25 13:41

    I don't have any project where I can try right now.

    But you might want to try this :

    let action = [SKAction runBlock:^{
        double randTime = 1.5; // do your arc4random here instead of fixed value
        let moveRight = SKAction.moveByX(frame.size.width/2.8, y: 0, duration: randTime)
        let moveLeft = SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: randTime)
        let texRight = SKAction.setTexture(SKTexture(imageNamed: "Drake2"))
        let texLeft = SKAction.setTexture(SKTexture(imageNamed: "Drake1"))
    
        let sequence = SKAction.sequence([texRight, moveRight, texLeft, moveLeft])
    
        Drake1.runAction(sequence)
    }]; 
    
    let repeatAction = SKAction.repeatActionForever(action)
    
    Drake1.runAction(repeatAction)
    

    Let me know if it helped.

    0 讨论(0)
提交回复
热议问题