Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey I have this project in which the player is supposed to go up like Mega Jump and I want to animate the player so that when it goes left or right or down it changes its image according to it. Any ideas how I can achieve this? This is my code where I create the player.

func createPlayer() -> SKNode {

    let playerNode = SKNode()
    playerNode.position = CGPoint(x: self.size.width / 2, y: 80.0)
    var spriteTexture = SKTexture(imageNamed: "IMAGE")
    var sprite = SKSpriteNode(texture: spriteTexture)

    if (playerNode.physicsBody?.velocity.dx < 0) && (playerNode.physicsBody?.velocity.dy > 0) {

        sprite = SKSpriteNode(imageNamed: "LEFT")
        let frames = [
            SKTexture(imageNamed: "LEFT"),
        ]
        let duration = 0.5
        let move = SKAction.animateWithTextures(frames, timePerFrame:0.25)
        let wait = SKAction.waitForDuration(duration)
        let rest = SKAction.setTexture(frames[0])
        let sequence = SKAction.sequence([wait, move, wait, rest])
        sprite.runAction(sequence)


    } else if (playerNode.physicsBody?.velocity.dx > 0) && (playerNode.physicsBody?.velocity.dy > 0){

        sprite = SKSpriteNode(imageNamed: "RIGHT")
        let frames = [
            SKTexture(imageNamed: "RIGHT"),
        ]
        let duration = 0.5
        let move = SKAction.animateWithTextures(frames, timePerFrame:0.25)
        let wait = SKAction.waitForDuration(duration)
        let rest = SKAction.setTexture(frames[0])
        let sequence = SKAction.sequence([wait, move, wait, rest])
        sprite.runAction(sequence)

    }
    playerNode.addChild(sprite)



    playerNode.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width / 2)
    playerNode.physicsBody?.dynamic = false
    playerNode.physicsBody?.allowsRotation = false
    playerNode.physicsBody?.restitution = 1.0
    playerNode.physicsBody?.friction = 0.0
    playerNode.physicsBody?.angularDamping = 0.0
    playerNode.physicsBody?.linearDamping = 0.0
    playerNode.physicsBody?.usesPreciseCollisionDetection = true
    playerNode.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Player
    playerNode.physicsBody?.collisionBitMask = 0
    playerNode.physicsBody?.contactTestBitMask = CollisionCategoryBitmask.Star | CollisionCategoryBitmask.Platform | CollisionCategoryBitmask.Monster


    return playerNode
} 

I don't know if im on track or doing it all wrong, I am still learning sprite kit and swift. But if anyone could help me achieve this I would appreciate it! Thank you in advance
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900