近期发布
专辑列表

Windows Phone 游戏合集
JQueryElement
IEBrowser
WPXNA

XNA 通过图片播放动画,Windows Phone 游戏开发

本文将介绍如何将正副的图片作为动画显示。

准备图片

我们需要逐帧的绘制你想要的动画效果,下面的一副图片仅仅是一个例子,假定一个角色所占的大小为 50x50。

添加图片

将已经绘制好的图片添加到 Content 项目中。

载入图片

在 Game 类的 LoadContent 方法中,我们使用 Content 的 Load 方法来加载准备好的图片(这个方法还可以载入其它资源)。这里需要设置正确的路径 @"image/test",test 是图片的资产名称。最后,我们将图片保存在 textImage 字段。

private Texture2D textImage;           
protected override void LoadContent ( )           
{           
    // 创建新的 SpriteBatch,可将其用于绘制纹理。           
    spriteBatch = new SpriteBatch ( GraphicsDevice );           
                       
    // TODO: 在此处使用 this.Content 加载游戏内容           
    this.textImage = this.Content.Load<Texture2D> (           
        @"image/test"
    );           
}

 

更新帧信息

播放动画的原理是绘制图片的不同部分,中间有一定的时间间隔,这样看上去就像角色在动一样。因此,首先需要设置每隔多久更新绘制的区域。

private int frameIndex = 1;         
private int frameWait = 30;         
protected override void Update ( GameTime gameTime )         
{         
                   
    if ( --this.frameWait == 0 )         
    {         
        this.frameWait = 30;         
                   
        if ( ++this.frameIndex == 3 )         
            this.frameIndex = 1;         
                   
    }         
                   
    base.Update ( gameTime );         
}

在上面的代码中,frameIndex 表示当前绘制图片的哪一个部分,以尺寸 50x50 为分隔,frameWait 表示下一次更新 frameIndex 还需要多少帧。每一隔 30 帧大约 1 秒钟,我们在图片的第一部分和第二部分之间切换。

绘制图片

最后,我们在 Game 的 Draw 方法中根据 frameIndex 来绘制图片的一部分就行了。

protected override void Draw ( GameTime gameTime )     
{     
    GraphicsDevice.Clear ( Color.CornflowerBlue );     
           
    this.spriteBatch.Begin ( );     
    this.spriteBatch.Draw (     
        this.textImage,     
        Vector2.Zero,     
        new Rectangle (     
            50 * ( this.frameIndex - 1 ),     
            0,     
            50, 50 ),     
        Color.White     
        );     
    this.spriteBatch.End ( );     
           
    base.Draw ( gameTime );     
}

上面的代码中,我们在原点绘制了图片,并根据 frameIndex 确定了需要绘制的区域。

 

 

所在专辑:http://throw.diandian.com/post/xna-base

原文地址:http://throw.diandian.com/post/xna-image

posted @ 2012-09-30 20:48  麦丝平方  阅读(1750)  评论(1编辑  收藏  举报