Swift语言实战晋级-第9章 游戏实战-跑酷熊猫-4 熊猫的跳和打滚

之前我们学会了跑的动作,现在我们可以利用同样的方法来实现了跳和打滚的动画。

 

……

 

class Panda : SKSpriteNode {

   ……

    //跳的纹理集合

    let jumpAtlas = SKTextureAtlas(named: "jump.atlas")

    //存储跳的文理的数组

    let jumpFrames = [SKTexture]();

    //打滚的文理集合

    let rollAtlas = SKTextureAtlas(named: "roll.atlas")

    //存储打滚文理的数组

    let rollFrames = [SKTexture]();

 

   

    var status = Status.run

    //构造器

    override init(){

        ……

        //填充跳的纹理数组

        for i=1 ; i<=jumpAtlas.textureNames.count ; i++ {

            let tempName = String(format: "panda_jump_%.2d", i)

            let jumpTexture = jumpAtlas.textureNamed(tempName)

            if jumpTexture != nil {

                jumpFrames.append(jumpTexture)

            }

        }

        //填充打滚的纹理数组

        for i=1 ; i<=rollAtlas.textureNames.count ; i++ {

            let tempName = String(format: "panda_roll_%.2d", i)

            let rollTexture = rollAtlas.textureNamed(tempName)

            if rollTexture != nil{

                rollFrames.append(rollTexture)

            }

        }

    }

    func run(){

       ^

    }

    //跳

    func jump (){

        self.removeAllActions()

        status = .jump

        self.runAction(SKAction.animateWithTextures(jumpFrames, timePerFrame: 0.05))

    }

    //打滚

    func roll(){

        self.removeAllActions()

        status = .roll

        self.runAction(SKAction.animateWithTextures(rollFrames, timePerFrame: 0.05),completion:{() in self.run()})

    }

 

    required init(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

}

 

注意:

由于跳和打滚的动作不像跑的动作需要循环播放,所以就不需要用repeatActionForever。打滚动作结束后就执行跑步动作。而跳跃动作由于不知道什么时候落地,所以将会由外部控制它的动作转变。

 

完成了以上的代码,我们怎么能验证我们的代码没有错呢?让我们打开GameScene,写一个响应屏幕点击的方法,简单的写个逻辑来测试跳和打滚动作没写错。代码如下:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
//当熊猫状态为跑的时候播放跳的动作
if panda.status == Status.run {
panda.jump()
}else if panda.status == Status.jump {
//当状态为跳的时候,执行打滚动画
panda.roll()
}
}

 

    运行代码,我们会发现跑跳滚的动画都很正确的执行了。当然这段代码只是演示用的,过后要删除。

 

我的微信公众号

我写的破书:《Swift语言实战晋级》http://item.jd.com/11641501.html

posted on 2015-02-10 12:00  老镇  阅读(737)  评论(0编辑  收藏  举报

导航