简体   繁体   中英

Animate Sprite moving left and right being controlled by Player Swift

I have a SpaceShooter game. I have been trying to make it look better by adding animations to it. I currently have a boss battle in the game and I added about 17 images that cycle through.

I managed to cycle the textures of something that isn't controller by the player but how would I add textures to the players sprite?

The player controls a Space Fighter ship left and right on the x axis. I have 5 images total I want to use (Left 2, left 1, center, right 1, right 2)

No doubt I would have to use switch case or if statements to do that but what would I need to input to let xcode know that I would want the sprite to switch only when moved and switch back its not being moved left or right?

I tried something earlier and I put the NSLogs just to see if it outputs "left" or "right" if i moved it left or right but it just outputs right for some reason

Here is the code I have for the player

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        /* Called when a touch begins */

        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)

            Player.position.x = location.x

        }
    }

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        var previousPosition: CGFloat = 0

        Player.position.x = location.x

        if Player.position.x > previousPosition
        {
            NSLog("Right")
            // add textures here
        }
        else if Player.position.x < previousPosition
        {
            NSLog("Left")
            // add textures here
        }
       previousPosition = Player.position.x

Im pretty sure this will do the trick. All you have to do is just change the texture of the Player to the desired texture.

for touch: AnyObject in touches {
    let location = touch.locationInNode(self)
    var previousPosition: CGFloat = 0

    Player.position.x = location.x

    if Player.position.x > previousPosition
    {
        NSLog("Right")
        // add textures here
        Player.texture = SKTexture(imageNamed: "RightImage")
    }
    else if Player.position.x < previousPosition
    {
        NSLog("Left")
        // add textures here
        Player.texture = SKTexture(imageNamed: "LeftImage")
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM