简体   繁体   中英

MonoGame do I need to use Draw() - or can I just use Update()

I am new to MonoGame and am wondering why I need to have Draw and Update be separate function calls. It seems somewhat inefficient, for example in both functions I loop over 1000 entities and call update, why can't I just draw inside that update function instead of performing 2 loops.

For example:

// more efficient - 1 loop
// In Update Function
foreach (var entity in entities) {
  entity.Update();
  entity.Draw();
}

versus

// Less efficient - 2 loops over entities
// In Update Function
foreach (var entity in entities) entity.Update();

// In Draw Function
foreach (var entity in entities) entity.Draw();

Do I actually need the Draw function at all? Or can I just do all my drawing in the Update function?

Yes, the Draw() call can be used as a way to separate your updates from your draws, as they happen much less often and need the most optimization.

For example, when the game is running in the background (ie you click on the "_" button on the window) you might want the game to keep running at half the refresh rate (So every odd frame would be skipped) or simply keep it from rendering anything and keep the game running in the background with minimal physics calculations, etc.

So during your Game class' draw() call, you might check for whether the window is running in the background or not, and decide to skip drawing on every odd frame, like so :

if (!Game.IsActive && (someBoolean = !someBoolean))
{
    return;
}

Where someBoolean is a boolean that will switch from true to false and vice-versa every frame, ensuring you'll run at half frames when the game window isn't active.

Or you could straight up make it not render/run when inactive and not have an extra boolean.

It's one of the best practices for making games, and a great way to separate concerns, and if you use the vanilla Game.Components system, you'll want to separate your draw() calls from your update() calls to prevent any side-effects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM