如何基于速度为sprite设置动画?

时间:2015-03-27 01:01:52

标签: swift xcode6 sprite-kit

嘿,我有这个项目,其中玩家应该像Mega Jump一样上升,我想让玩家动画,这样当它向左或向右或向下时,它会根据它改变它的图像。我有什么想法可以达到这个目的吗?这是我创建播放器的代码。

class GameScene: SKScene, SKPhysicsContactDelegate  {

let foregroundNode = SKNode()
let player = SKNode()

override init(size: CGSize) {
    super.init(size: size)

    physicsWorld.gravity = CGVector(dx: 0.0, dy: -3.0)
    physicsWorld.contactDelegate = self

    foregroundNode = SKNode()
    addChild(foregroundNode)

    player = createPlayer()
    foregroundNode.addChild(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)
    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
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if player.physicsBody!.dynamic {
        return
    }
    tapToStartNode.removeFromParent()
    player.physicsBody?.dynamic = true
    player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 30.0))

}

override func update(currentTime: NSTimeInterval) {

    var spriteTexture = SKTexture(imageNamed: "IMAGE")
    var sprite = SKSpriteNode(texture: spriteTexture)
    if (player.physicsBody?.velocity.dx < 0) && (player.physicsBody?.velocity.dy > 0) {

        sprite.texture = SKTexture(imageNamed: "IMAGE LEFT")


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

        sprite.texture = SKTexture(imageNamed: "IMAGE RIGHT")

    }

我不知道如果我在轨道上或做错了,我仍在学习精灵套件和swift。但如果有人能帮助我实现这一目标,我将不胜感激!提前谢谢

2 个答案:

答案 0 :(得分:0)

如果您计划为图像设置动画,则不应直接使用图像制作精灵节点。而是使用图像名称初始化SKTexture。现在,您可以使用该纹理制作精灵节点。从那时起,只使用纹理,因为每个精灵节点都有一个texture属性,您可以直接设置 - sprite.texture

答案 1 :(得分:0)

您可以在更新方法中执行此操作:

Update()
{
    if(player.velocity.dx < 0 && sprite.texture != self.rightTexture)
          sprite.texture = self.rightTexture;
    else if(player.velocity.dx > 0 && sprite.texture != self.leftTexture)
          sprite.texture = self.leftTexture;
    //Add checks for down or up.  Order it based on what takes priority.

}

此代码贯穿每一帧并根据其速度更新纹理。在开头加载纹理,然后重复使用它们以节省内存和性能。