Xna 4.0 WP,SpriteBatch - 动画

时间:2014-02-18 16:45:34

标签: xna windows-phone

我有这段代码:

public class Game1 : Microsoft.Xna.Framework.Game
{          
    SpriteBatch spriteBatch;
    Vector2 m = new Vector2(0, 0);  
    Texture2D polska;        
    int i = 1;

    //Game class boilerplate code snipped for brevity.

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void Draw(GameTime gameTime)
    {
        polska = Content.Load<Texture2D>(i.ToString());
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(polska, m, null, Color.White);
        spriteBatch.End();

        if (i == 169)
            i = 1;
        else
            i++;

        base.Draw(gameTime);              
    }          
}

问题是当我在手机上运行时,它只显示1张图像,它应该显示169张不同的图像(它们被命名为[number].png)。

有什么问题?

1 个答案:

答案 0 :(得分:2)

您真的不应该在Draw方法中加载内容,因为每次更新&gt; 30次,并且加载纹理需要时间。相反,在LoadContent方法中加载所有图像 ONCE (使用数组或列表存储它们),然后在Draw方法中绘制正确的图像:

Texture2D[] polska = new Texture2D[169];//array of textures

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    for (int j = 0; j < 169; j++)
        polska[j] = Content.Load<Texture2D>(j.ToString());//load all the images here


    // TODO: use this.Content to load your game content here
}


protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    spriteBatch.Begin();
    spriteBatch.Draw(polska[i],m,null,Color.White);//draw the current (i) image
    spriteBatch.End();
    if (i == 169)
    {
        i = 1;
    }
    else
    {
        i++;
    }
    base.Draw(gameTime);

}

HTH,如果有什么不清楚的话。

注意:正如@StevenHansen指出的那样,你应该调整你的纹理大小,这样就不会出现内存不足的情况。