How do I pause the redraw in XNA?

你离开我真会死。 提交于 2019-12-05 00:55:55

You can use the Game.SupressDraw method for this purpose. From the remarks at the link:

Call this method during Update to prevent any calls to Draw until after the next call to Update. This method can be used on small devices to conserve battery life if the display does not change as a result of Update. For example, if the screen is static with no background animations, the player input can be examined during Update to determine whether the player is performing any action. If no input is detected, this method allows the game to skip drawing until the next update.

As an example, the following code will only call the Draw function once. When I tested this I noticed that the CPU usage was high (70%) without the SuppressDraw call. When using SupressDraw, the CPU usage dropped dramatically (to less than 15%). Your numbers may vary.

public class Game1 : Microsoft.Xna.Framework.Game
{
    ...
    private bool _drawn = false;
    protected override void Update(GameTime gameTime)
    {
        if (_drawn)
            SuppressDraw();
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        /* draw stuff here */
        spriteBatch.End();

        _drawn = true;
    }
    ...
}

Note that SupressDraw only suppresses one Draw call. To prevent more calls to Draw, you have to continually call SupressDraw in Update. Hopefully that makes sense.

As the accepted answer says, you can use SuppressDraw to avoid drawing an unchanged frame. Your Update-method will run regardless, however, which is why it still uses more CPU than you expect. To avoid using as much CPU, you need to somehow avoid updating things you know haven't changed since the last frame.

I assume you would know this the same way as you know when to suppress draw, so what you need to do is rearrange your Update-method like this:

private void Update(GameTime gameTime)
{
    var frameHasChanges = DetectChanges(); //This method you need to figure out yourself
    if (!frameHasChanges)
    {
        SuppressDraw();
        base.Update(gameTime);
        return;
    }

    //Do the rest of normal Update

}

As a final note; I have never had to use this in any game I have ever made. Which I feel suggests you may have some other, underlying problem with performance. I have, however, used many techniques to avoid rendering text and so on each frame (causes boxing/unboxing). Ask about this in comment if you want to know more.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!