aboutsummaryrefslogtreecommitdiff
path: root/files/es/games/anatomy/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/es/games/anatomy/index.html')
-rw-r--r--files/es/games/anatomy/index.html325
1 files changed, 0 insertions, 325 deletions
diff --git a/files/es/games/anatomy/index.html b/files/es/games/anatomy/index.html
deleted file mode 100644
index 799f31f931..0000000000
--- a/files/es/games/anatomy/index.html
+++ /dev/null
@@ -1,325 +0,0 @@
----
-title: Anatomy of a video game
-slug: Games/Anatomy
-tags:
- - Bucle
- - JavaScript
- - juegos
-translation_of: Games/Anatomy
----
-<div>{{GamesSidebar}}</div><p>{{IncludeSubnav("/en-US/docs/Games")}}</p>
-
-<div class="summary">
-<p><span class="seoSummary">Este artículo es un vistazo a la anatomía y flujo de trabajo del videojuego medio desde un punto de vista técnico, en términos de cómo debería funcionar el bucle principal. Ayuda a los principiantes del desarrollo moderno de videojuegos a entender lo que hace falta al construir un juego y cómo los estándares web como JavaScript se prestan como herramientas. Los programadores de juegos experimentados que sean novatos en el desarrollo web también se pueden beneficiar.</span></p>
-</div>
-
-<h2 id="Presentar_aceptar_traducir_calcular_repetir">Presentar, aceptar, traducir, calcular, repetir</h2>
-
-<p>El objetivo de todo videojuego es <strong>presentar</strong> al usuario una situación, <strong>aceptar</strong> su entrada, <strong>traducir</strong> esas señales a acciones, y <strong>calcular</strong> una nueva situación a partir de esos actos. Los juegos están iterando continuamente por estas etapas, una y otra vez, hasta que ocurre alguna condición final (como ganas, perder, o salirse para ir a la cama). De forma poco sorpresiva, este patrón corresponde a cómo se programa el motor de un juego.</p>
-
-<p>Los detalles dependen del juego.</p>
-
-<p>Algunos juegos dirigen este ciclo con la entrada del usuario. Imagina que estás desarrollando un juego del tipo <em>"encuentra las diferencias entre estas dos imágenes similares"</em>. Estos juegos <strong>presentan</strong> dos imágenes al usuario; <strong>aceptan</strong> sus clics (o toques); <strong>interpretan</strong> la entrada como éxito, fallo, pausa, interacción del menú, etc; y finalmente, calculan una escena actualizada resultante de esa entrada. El bucle del juego avanza con la entrada del usuario, y se queda en espera hasta que ésta se produce. Esto es más bien un enfoque basado por turnos que no requiere una actualización constante cada frame, sólo cuando el jugador reacciona.</p>
-
-<p>Otros juegos requieren control sobre cada uno de los más pequeños aspectos posibles. Se aplican los mismos principios de antes, con una ligera variación: cada frame de la animación hace progresar el ciclo, y cualquier cambio en la entrada del usuario se captura en el primer turno disponible. Este modelo de <em>una-vez-por-frame</em> se implementa en algo llamado <strong>bucle principal</strong>. Si el bucle de tu juego está basado en tiempo, éste será una ley a la que se tendrán que atener tus simulaciones.</p>
-
-<p>Pero puede no necesitar de un control <em>por-frame</em>. El bucle de tu juego podría ser similar al ejemplo de <em>encuentra las diferencias</em>, y basarse en las entradas del usuario. Podría necesitar tanto entradas como tiempo simulado. Podría incluso estar totalmente basado en algo diferente.</p>
-
-<p>Por suerte, el JavaScript moderno (que se describe en las siguientes secciones) hace sencillo desarrollar un bucle principal eficiente, tipo <em>ejecutar-una-vez-por-frame</em>. Por supuesto, estará tan optimizado como tú lo hagas. Si algo parece que debería ir acoplado a un evento más infrecuente, suele ser una buena idea (aunque no siempre) sacarlo fuera del bucle principal.</p>
-
-<h2 id="Crear_un_bucle_principal_en_JavaScript">Crear un bucle principal en JavaScript</h2>
-
-<p>JavaScript funciona mejor con eventos y funciones callback. Los navegadores modernos se esfuerzan en invocar los métodos sólo en cuanto se necesita, y reposar (o hacer otras tareas) en los intervalos. Es una idea excelente añadir tu código a los momentos apropiados. Considera si tu función necesita de verdad ser invocada en un intervalo estricto de tiempo, a cada frame, o sólo cuando haya ocurrido alguna otra cosa. Especificándole al navegador cuándo tiene que ser invocada tu función le permite optimizarla. Además, probablemente haga tu trabajo más fácil.</p>
-
-<p>Algún código necesita ejecutarse frame a frame, así que ¿por qué añadir esa función a cualquier otra cosa que al planificador de redibulado del navegador? En la web, <code>{{ domxref("window.requestAnimationFrame()") }} </code>será la base de la mayoría de bucles principales frame-a-frame bien programados. Al invocarla, hay que pasarle una función callback. Esa función callback se ejecutará en el momento apropiado antes del próximo redibujado. Aquí hay un ejemplo de un bucle principal sencillo:</p>
-
-<pre>window.main = function () {
- window.requestAnimationFrame( main );
-
- // Lo que sea que tenga que hacer tu bucle principal
-};
-
-main(); // Empezar el ciclo</pre>
-
-<p><strong>Note</strong>: In each of the <code>main()</code> methods discussed here, we schedule a new <code>requestAnimationFrame</code> before performing our loop contents. That is not by accident and it is considered best practice. Calling the next <code>requestAnimationFrame</code> early ensures the browser receives it on time to plan accordingly even if your current frame misses its VSync window.</p>
-
-<p>The above chunk of code has two statements. The first statement creates a function as a global variable called <code>main()</code>. This function does some work and also tells the browser to call itself next frame with <code>window.requestAnimationFrame()</code>. The second statement calls the <code>main()</code> function, defined in the first statement. Because <code>main()</code> is called once in the second statement and every call of it places itself in the queue of things to do next frame, <code>main()</code> is synchronized to your framerate.</p>
-
-<p>Of course this loop is not perfect. Before we discuss ways to change it, let us discuss what it already does well.</p>
-
-<p>Timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. You are given control over each frame of animation. It is also very simple because <code>main()</code> is the only function getting looped. A First Person Shooter (or a similar game) presents a new scene once every frame. You cannot really get more smooth and responsive than that.</p>
-
-<p>But do not immediately assume animations require frame-by-frame control. Simple animations can be easily performed, even GPU-accelerated, with CSS animations and other tools included in the browser. There are a lot of them and they will make your life easier.</p>
-
-<h2 id="Building_a_better_main_loop_in_Javascript">Building a <em>better</em> main loop in Javascript</h2>
-
-<p>There are two obvious issues with our previous main loop: <code>main()</code> pollutes the <code>{{ domxref("window") }}</code> object (where all global variables are stored) and the example code did not leave us with a way to <em>stop</em> the loop unless the whole tab is closed or refreshed. For the first issue, if you want the main loop to just run and you do not need easy (direct) access to it, you could create it as an Immediately-Invoked Function Expression (IIFE).</p>
-
-<pre>/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*/
-
-;(function () {
- function main() {
- window.requestAnimationFrame( main );
-
- // Your main loop contents.
- }
-
- main(); // Start the cycle
-})();</pre>
-
-<p>When the browser comes across this IIFE, it will define your main loop and immediately queue it for the next frame. It will not be attached to any object and <code>main</code> (or <code>main()</code> for methods) will be a valid unused name in the rest of the application, free to be defined as something else.</p>
-
-<p>Note: In practice, it is more common to prevent the next requestAnimationFrame() with an if-statement, rather than calling cancelAnimationFrame().</p>
-
-<p>For the second issue, stopping the main loop, you will need to cancel the call to <code>main()</code> with <code>{{ domxref("window.cancelAnimationFrame()") }}</code>. You will need to pass <code>cancelAnimationFrame()</code> the ID token given by <code>requestAnimationFrame()</code> when it was last called. Let us assume that your game's functions and variables are built on a namespace that you called <code>MyGame</code>. Expanding our last example, the main loop would now look like:</p>
-
-<pre>/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
- function main() {
- MyGame.stopMain = window.requestAnimationFrame( main );
-
- // Your main loop contents.
- }
-
- main(); // Start the cycle
-})();</pre>
-
-<p>We now have a variable declared in our <code>MyGame</code> namespace, which we call <code>stopMain</code>, that contains the ID returned from our main loop's most recent call to <code>requestAnimationFrame()</code>. At any point, we can stop the main loop by telling the browser to cancel the request that corresponds to our token.</p>
-
-<pre>window.cancelAnimationFrame( MyGame.stopMain );</pre>
-
-<p>The key to programming a main loop, in JavaScript, is to it attach to whatever event should be driving your action and pay attention to how the different systems involved interplay. You may have multiple components driven by multiple different types of events. This feels like unnecessary complexity but it might just be good optimization (not necessarily, of course). The problem is that you are not programming a typical main loop. In Javascript, you are using the browser's main loop and you are trying to do so effectively.</p>
-
-<h2 id="Building_a_more_optimized_main_loop_in_JavaScript">Building a <em>more</em> <em>optimized</em> main loop in JavaScript</h2>
-
-<p>Ultimately, in JavaScript, the browser is running its own main loop and your code exists in some of its stages. The above sections describe main loops which try not to wrestle away control from the browser. These main methods attach themselves to <code>window.requestAnimationFrame()</code>, which asks the browser for control over the upcoming frame. It is up to the browser how to relate these requests to their main loop. The <a href="http://www.w3.org/TR/animation-timing/">W3C spec for requestAnimationFrame</a> does not really define exactly when the browsers must perform the requestAnimationFrame callbacks. This can be a benefit because it leaves browser vendors free to experiment with the solutions that they feel are best and tweak it over time.</p>
-
-<p>Modern versions of Firefox and Google Chrome (and probably others) <em>attempt</em> to connect <code>requestAnimationFrame</code> callbacks to their main thread at the very beginning of a frame's timeslice. The browser's main thread thus <em>tries</em> to look like the following:</p>
-
-<ol>
- <li>Start a new frame (while the previous frame is handled by the display).</li>
- <li>Go through the list of <code>requestAnimationFrame</code> callbacks and invoke them.</li>
- <li>Perform garbage collection and other per-frame tasks when the above callbacks stop controlling the main thread.</li>
- <li>Sleep (unless an event interrupts the browser's nap) until the monitor is ready for your image (<a href="http://www.techopedia.com/definition/92/vertical-sync-vsync">VSync</a>) and repeat.</li>
-</ol>
-
-<p>You can think about developing realtime applications as having a budget of time to do work. All of the above steps must take place every 16-and-a-half milliseconds to keep up with a 60 Hz display. Browsers invoke your code as early as possible to give it maximum computation time. Your main thread will often start workloads that are not even on the main thread (such as rasterization or shaders in WebGL). Long calculations can be performed on a Web Worker or a GPU at the same time as the browser uses its main thread to manage garbage collection, its other tasks, or handle asynchronous events.</p>
-
-<p>While we are on the topic of budgeting time, many web browsers have a tool called <em>High Resolution Time</em>. The {{ domxref("Date") }} object is no longer the recognised method for timing events because it is very imprecise and can be modified by the system clock. High Resolution Time, on the other hand, counts the number of milliseconds since <code>navigationStart</code> (when the previous document is unloaded). This value is returned as a decimal number accurate to a thousandth of a millisecond. It is known as a <code>{{ domxref("DOMHighResTimeStamp") }}</code> but, for all intents and purposes, consider it a floating point number.</p>
-
-<p><strong>Note</strong>: Systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. They should provide 0.001ms accuracy if they are capable of it, however.</p>
-
-<p>This value is not too useful alone, since it is relative to a fairly uninteresting event, but it can be subtracted from another timestamp to accurately and precisely determine how much time elapsed between those two points. To acquire one of these timestamps, you can call <code>window.performance.now()</code> and store the result as a variable.</p>
-
-<pre>var tNow = window.performance.now();
-</pre>
-
-<p>Back to the topic of the main loop. You will often want to know when your main function was invoked. Because this is common, <code>window.requestAnimationFrame()</code> always provides a <code>DOMHighResTimeStamp</code> to callbacks as an argument when they are executed. This leads to another enhancement to our previous main loops.</p>
-
-<pre>/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
- function main( tFrame ) {
- MyGame.stopMain = window.requestAnimationFrame( main );
-
- // Your main loop contents.
- // tFrame, from "function main ( tFrame )", is now a DOMHighResTimeStamp provided by rAF.
- }
-
- main(); // Start the cycle
-})();</pre>
-
-<p>Several other optimizations are possible and it really depends on what your game attempts to accomplish. Your game genre will obviously make a difference but it could even be more subtle than that. You could draw every pixel individually on a canvas or you could layer DOM elements (including multiple WebGL canvases with transparent backgrounds if you want) into a complex hierarchy. Each of these paths will lead to different opportunities and constraints.</p>
-
-<h2 id="It_is_decision..._time">It is decision... time</h2>
-
-<p>You will need to make hard decisions about your main loop: how to simulate the accurate progress of time. If you demand per-frame control then you will need to determine how frequently your game will update and draw. You might even want update and draw to occur at different rates. You will also need to consider how gracefully your game will fail if the user's system cannot keep up with the workload. Let us start by assuming that you will handle user input and update the game state every time you draw. We will branch out later.</p>
-
-<p><em><strong>Note</strong>: </em>Changing how your main loop deals with time is a debugging nightmare, everywhere. Think about your needs, carefully, before working on your main loop.</p>
-
-<h3 id="What_most_browser_games_should_look_like">What most browser games should look like</h3>
-
-<p>If your game can hit the maximum refresh rate of any hardware you support then your job is fairly easy. You can simply update, render, and then do nothing until VSync.</p>
-
-<pre>/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
- function main( tFrame ) {
- MyGame.stopMain = window.requestAnimationFrame( main );
-
- update( tFrame ); //Call your update method. In our case, we give it rAF's timestamp.
- render();
- }
-
- main(); // Start the cycle
-})();</pre>
-
-<p>If the maximum refresh rate cannot be reached, quality settings could be adjusted to stay under your time budget. The most famous example of this concept is the game from id Software, RAGE. This game removed control from the user in order to keep its calculation time at roughly 16ms (or roughly 60fps). If computation took too long then rendered resolution would decrease, textures and other assets would fail to load or draw, and so forth. This (non-web) case study made a few assumptions and tradeoffs:</p>
-
-<ul>
- <li>Each frame of animation accounts for user input.</li>
- <li>No frame needs to be extrapolated (guessed) because each draw has its own update.</li>
- <li>Simulation systems can basically assume that each full update is ~16ms apart.</li>
- <li>Giving the user control over quality settings would be a nightmare.</li>
- <li>Different monitors input at different rates: 30 FPS, 75 FPS, 100 FPS, 120 FPS, 144 FPS, etc.</li>
- <li>Systems that are unable to keep up with 60 FPS lose visual quality to keep the game running at optimal speed (eventually it outright fails, if quality becomes too low.)</li>
-</ul>
-
-<h3 id="Other_ways_to_handle_variable_refresh_rate_needs">Other ways to handle variable refresh rate needs</h3>
-
-<p>Other methods of tackling the problem exist.</p>
-
-<p>One common technique is to update the simulation at a constant frequency and then draw as much (or as little) of the actual frames as possible. The update method can continue looping without care about what the user sees. The draw method can view the last update and when it happened. Since draw knows when it represents, and the simulation time for the last update, it can predict a plausible frame to draw for the user. It does not matter whether this is more frequent than the official update loop (or even less frequent). The update method sets checkpoints and, as frequently as the system allows, the render method draws instants of time around them. There are many ways to separate the update method in web standards:</p>
-
-<ul>
- <li>Draw on <code>requestAnimationFrame</code> and update on a {{ domxref("window.setInterval") }} or {{ domxref("window.setTimeout") }}.
-
- <ul>
- <li>This uses processor time even when unfocused or minimized, hogs the main thread, and is probably an artifact of traditional game loops (but it is simple.)</li>
- </ul>
- </li>
- <li>Draw on <code>requestAnimationFrame</code> and update on a <code>setInterval</code> or <code>setTimeout</code> in a <a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Web Worker</a>.
- <ul>
- <li>This is the same as above, except update does not hog the main thread (nor does the main thread hog it). This is a more complex solution, and might be too much overhead for simple updates.</li>
- </ul>
- </li>
- <li>Draw on <code>requestAnimationFrame</code> and use it to poke a Web Worker containing the update method with the number of ticks to compute, if any.
- <ul>
- <li>This sleeps until <code>requestAnimationFrame</code> is called and does not pollute the main thread, plus you are not relying on old fashioned methods. Again, this is a bit more complex than the previous two options, and <em>starting</em> each update will be blocked until the browser decides to fire rAF callbacks.</li>
- </ul>
- </li>
-</ul>
-
-<p>Each of these methods have similar tradeoffs:</p>
-
-<ul>
- <li>Users can skip rendering frames or interpolate extra ones depending on their performance.</li>
- <li>You can count on all users updating non-cosmetic variables at the same constant frequency minus hiccups.</li>
- <li>Much more complicated to program than the basic loops we saw earlier.</li>
- <li>User input is completely ignored until the next update (even if the user has a fast device).</li>
- <li>The mandatory interpolation has a performance penalty.</li>
-</ul>
-
-<p>A separate update and draw method could look like the following example. For the sake of demonstration, the example is based on the third bullet point, just without using Web Workers for readability (and, let's be honest, writeability).</p>
-
-<p><em>Note: This example, specifically, is in need of technical review.</em></p>
-
-<pre>/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*
-* MyGame.lastRender keeps track of the last provided requestAnimationFrame timestamp.
-* MyGame.lastTick keeps track of the last update time. Always increments by tickLength.
-* MyGame.tickLength is how frequently the game state updates. It is 20 Hz (50ms) here.
-*
-* timeSinceTick is the time between requestAnimationFrame callback and last update.
-* numTicks is how many updates should have happened between these two rendered frames.
-*
-* render() is passed tFrame because it is assumed that the render method will calculate
-* how long it has been since the most recently passed update tick for
-* extrapolation (purely cosmetic for fast devices). It draws the scene.
-*
-* update() calculates the game state as of a given point in time. It should always
-* increment by tickLength. It is the authority for game state. It is passed
-* the DOMHighResTimeStamp for the time it represents (which, again, is always
-* last update + MyGame.tickLength unless a pause feature is added, etc.)
-*
-* setInitialState() Performs whatever tasks are leftover before the mainloop must run.
-* It is just a generic example function that you might have added.
-*/
-
-;(function () {
- function main( tFrame ) {
- MyGame.stopMain = window.requestAnimationFrame( main );
- var nextTick = MyGame.lastTick + MyGame.tickLength;
- var numTicks = 0;
-
- //If tFrame &lt; nextTick then 0 ticks need to be updated (0 is default for numTicks).
- //If tFrame = nextTick then 1 tick needs to be updated (and so forth).
- //Note: As we mention in summary, you should keep track of how large numTicks is.
- //If it is large, then either your game was asleep, or the machine cannot keep up.
- if (tFrame &gt; nextTick) {
- var timeSinceTick = tFrame - MyGame.lastTick;
- numTicks = Math.floor( timeSinceTick / MyGame.tickLength );
- }
-
- queueUpdates( numTicks );
- render( tFrame );
- MyGame.lastRender = tFrame;
- }
-
- function queueUpdates( numTicks ) {
- for(var i=0; i &lt; numTicks; i++) {
- MyGame.lastTick = MyGame.lastTick + MyGame.tickLength; //Now lastTick is this tick.
- update( MyGame.lastTick );
- }
- }
-
- MyGame.lastTick = performance.now();
- MyGame.lastRender = MyGame.lastTick; //Pretend the first draw was on first update.
- MyGame.tickLength = 50; //This sets your simulation to run at 20Hz (50ms)
-
- setInitialState();
- main(performance.now()); // Start the cycle
-})();</pre>
-
-<p>Another alternative is to simply do certain things less often. If a portion of your update loop is difficult to compute but insensitive to time, you might consider scaling back its frequency and, ideally, spreading it out into chunks throughout that lengthened period. An implicit example of this is found over at The Artillery Blog for Artillery Games, where they <a href="http://blog.artillery.com/2012/10/browser-garbage-collection-and-framerate.html">adjust their rate of garbage generation</a> to optimize garbage collection. Obviously, cleaning up resources is not time sensitive (especially if tidying is more disruptive than the garbage itself).</p>
-
-<p>This may also apply to some of your own tasks. Those are good candidates to throttle when available resources become a concern.</p>
-
-<h2 id="Summary">Summary</h2>
-
-<p>I want to be clear that any of the above, or none of them, could be best for your game. The correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this but I have heard it is an excruciating game of Whack-a-Mole.</p>
-
-<p>An important thing to remember for managed platforms, like the web, is that your loop may stop execution for significant periods of time. This could occur when the user unselects your tab and the browser sleeps (or slows) its <code>requestAnimationFrame</code> callback interval. You have many ways to deal with this situation and this could depend on whether your game is single player or multiplayer. Some choices are:</p>
-
-<ul>
- <li>Consider the gap "a pause" and skip the time.
- <ul>
- <li>You can probably see how this is problematic for most multiplayer games.</li>
- </ul>
- </li>
- <li>You can simulate the gap to catch up.
- <ul>
- <li>This can be a problem for long drops and/or complex updates.</li>
- </ul>
- </li>
- <li>You can recover the game state from a peer or the server.
- <ul>
- <li>This is ineffective if your peers or server are out-of-date too, or they don't exist because the game is single player and doesn't have a server.</li>
- </ul>
- </li>
-</ul>
-
-<p>Once your main loop has been developed and you have decided on a set of assumptions and tradeoffs which suit your game, it is now just a matter of using your decisions to calculate any applicable physics, AI, sounds, network synchronization, and whatever else your game may require.</p>