diff options
author | julieng <julien.gattelier@gmail.com> | 2021-10-02 17:20:24 +0200 |
---|---|---|
committer | SphinxKnight <SphinxKnight@users.noreply.github.com> | 2021-10-02 17:30:20 +0200 |
commit | 1407c8fdef01ecd0ffb8a8bd46e7113f119b9fde (patch) | |
tree | 30a56efd3eff3a01bd1611e1840fdbbfacf544a4 /files/fr/web/api/gamepad_api | |
parent | c05efa8d7ae464235cf83d7c0956e42dc6974103 (diff) | |
download | translated-content-1407c8fdef01ecd0ffb8a8bd46e7113f119b9fde.tar.gz translated-content-1407c8fdef01ecd0ffb8a8bd46e7113f119b9fde.tar.bz2 translated-content-1407c8fdef01ecd0ffb8a8bd46e7113f119b9fde.zip |
convert content to md
Diffstat (limited to 'files/fr/web/api/gamepad_api')
-rw-r--r-- | files/fr/web/api/gamepad_api/index.md | 103 | ||||
-rw-r--r-- | files/fr/web/api/gamepad_api/using_the_gamepad_api/index.md | 234 |
2 files changed, 176 insertions, 161 deletions
diff --git a/files/fr/web/api/gamepad_api/index.md b/files/fr/web/api/gamepad_api/index.md index 7e81e21b27..2548f041e8 100644 --- a/files/fr/web/api/gamepad_api/index.md +++ b/files/fr/web/api/gamepad_api/index.md @@ -3,88 +3,59 @@ title: Gamepad API slug: Web/API/Gamepad_API translation_of: Web/API/Gamepad_API --- -<div>{{DefaultAPISidebar("Gamepad API")}}</div> +{{DefaultAPISidebar("Gamepad API")}} -<p>L'<strong>API Gamepad</strong> est un moyen pour les développeurs d'accéder aux signaux provenant des manettes des jeu et des autres unités de commande du jeu d'y répondre de manière simple et systématiq. Il contient trois interfaces, deux événements et une fonction spécialisée, pour répondre aux manettes connectées et déconnectées, et pour accéder à d'autres informations sur les manettes elles-mêmes, ainsi que sur les boutons et autres commandes sur lesquels vous appuyez actuellement.</p> +L'**API Gamepad** est un moyen pour les développeurs d'accéder aux signaux provenant des manettes des jeu et des autres unités de commande du jeu d'y répondre de manière simple et systématiq. Il contient trois interfaces, deux événements et une fonction spécialisée, pour répondre aux manettes connectées et déconnectées, et pour accéder à d'autres informations sur les manettes elles-mêmes, ainsi que sur les boutons et autres commandes sur lesquels vous appuyez actuellement. -<h2 id="Interfaces">Interfaces</h2> +## Interfaces -<dl> - <dt><a href="/en-US/docs/Web/API/Gamepad"><code>Gamepad</code></a></dt> - <dd>Représente une manette de jeu / unités de commande du jeu connecté à l'ordinateur.</dd> - <dt><a href="/en-US/docs/Web/API/GamepadButton"><code>GamepadButton</code></a></dt> - <dd>Représente un bouton sur un gamepad connecté.</dd> - <dt><a href="/en-US/docs/Web/API/GamepadEvent"><code>GamepadEvent</code></a></dt> - <dd>L'objet d'événement qui déclenche des événements sur la manette de jeu contiguë de manière représentative.</dd> -</dl> +- [`Gamepad`](/en-US/docs/Web/API/Gamepad) + - : Représente une manette de jeu / unités de commande du jeu connecté à l'ordinateur. +- [`GamepadButton`](/en-US/docs/Web/API/GamepadButton) + - : Représente un bouton sur un gamepad connecté. +- [`GamepadEvent`](/en-US/docs/Web/API/GamepadEvent) + - : L'objet d'événement qui déclenche des événements sur la manette de jeu contiguë de manière représentative. -<h3 id="Extensions_de_manette_du_jeu_expérimentales">Extensions de manette du jeu expérimentales</h3> +### Extensions de manette du jeu expérimentales -<dl> - <dt><a href="/en-US/docs/Web/API/GamepadHapticActuator"><code>GamepadHapticActuator</code></a></dt> - <dd>Represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.</dd> - <dt><a href="/en-US/docs/Web/API/GamepadPose"><code>GamepadPose</code></a></dt> - <dd>Represents the pose of a controller (e.g. position and orientation in 3D space) in the case of a <a href="/en-US/docs/Web/API/WebVR_API">WebVR</a>controller.</dd> -</dl> +- [`GamepadHapticActuator`](/en-US/docs/Web/API/GamepadHapticActuator) + - : Represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. +- [`GamepadPose`](/en-US/docs/Web/API/GamepadPose) + - : Represents the pose of a controller (e.g. position and orientation in 3D space) in the case of a [WebVR](/en-US/docs/Web/API/WebVR_API)controller. -<p>See also the <a href="/en-US/docs/Web/API/Gamepad#Experimental_extensions_to_Gamepad">extensions to the Gamepad interface</a>, for features that allow you to access the above information.</p> +See also the [extensions to the Gamepad interface](/en-US/docs/Web/API/Gamepad#Experimental_extensions_to_Gamepad), for features that allow you to access the above information. -<h3 id="Extensions_à_d'autres_interfaces">Extensions à d'autres interfaces</h3> +### Extensions à d'autres interfaces -<h4 id="Navigator">Navigator</h4> +#### Navigator -<dl> - <dt>{{domxref("Navigator.getGamepads()")}}</dt> - <dd>An extension to the {{domxref("Navigator")}} object that returns an array of {{domxref("Gamepad")}} objects, one for each connected gamepad.</dd> -</dl> +- {{domxref("Navigator.getGamepads()")}} + - : An extension to the {{domxref("Navigator")}} object that returns an array of {{domxref("Gamepad")}} objects, one for each connected gamepad. -<h4 id="Window_events">Window events</h4> +#### Window events -<dl> - <dt>{{domxref("Window.ongamepadconnected")}}</dt> - <dd>Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).</dd> - <dt>{{domxref("Window.ongamepaddisconnected")}}</dt> - <dd>Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).</dd> -</dl> +- {{domxref("Window.ongamepadconnected")}} + - : Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires). +- {{domxref("Window.ongamepaddisconnected")}} + - : Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires). -<h2 id="Tutoriels_et_guides">Tutoriels et guides</h2> +## Tutoriels et guides -<ul> - <li><a href="/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API">Using the Gamepad API</a></li> - <li><a href="/en-US/docs/Games/Techniques/Controls_Gamepad_API">Implementing controls using the Gamepad API</a></li> -</ul> +- [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API) +- [Implementing controls using the Gamepad API](/en-US/docs/Games/Techniques/Controls_Gamepad_API) -<h2 id="Caractéristiques">Caractéristiques</h2> +## Caractéristiques -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Spécification</th> - <th scope="col">Statut</th> - <th scope="col">Commentaire</th> - </tr> - <tr> - <td>{{SpecName("GamepadExtensions")}}</td> - <td>{{Spec2("GamepadExtensions")}}</td> - <td>Defines the {{anch("Experimental Gamepad extensions")}}.</td> - </tr> - <tr> - <td>{{SpecName("Gamepad", "", "The Gamepad API specification")}}</td> - <td>{{Spec2("Gamepad")}}</td> - <td>Initial definition</td> - </tr> - </tbody> -</table> +| Spécification | Statut | Commentaire | +| -------------------------------------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------- | +| {{SpecName("GamepadExtensions")}} | {{Spec2("GamepadExtensions")}} | Defines the {{anch("Experimental Gamepad extensions")}}. | +| {{SpecName("Gamepad", "", "The Gamepad API specification")}} | {{Spec2("Gamepad")}} | Initial definition | -<h2 id="Compatibilité_du_navigateur">Compatibilité du navigateur</h2> +## Compatibilité du navigateur +{{Compat("api.Gamepad")}} +## Voir également -<p>{{Compat("api.Gamepad")}}</p> - -<h2 id="Voir_également">Voir également</h2> - -<ul> - <li><a href="https://hacks.mozilla.org/2013/12/the-gamepad-api/" rel="nofollow">The Gamepad API</a> by Ted Mielczarek and Robert Nyman</li> - <li><a href="http://luser.github.io/gamepadtest/">Simple API demo page</a> (<a href="https://github.com/luser/gamepadtest">source</a>)</li> -</ul> +- [The Gamepad API](https://hacks.mozilla.org/2013/12/the-gamepad-api/) by Ted Mielczarek and Robert Nyman +- [Simple API demo page](http://luser.github.io/gamepadtest/) ([source](https://github.com/luser/gamepadtest)) diff --git a/files/fr/web/api/gamepad_api/using_the_gamepad_api/index.md b/files/fr/web/api/gamepad_api/using_the_gamepad_api/index.md index d30dc4dce8..5a152773d4 100644 --- a/files/fr/web/api/gamepad_api/using_the_gamepad_api/index.md +++ b/files/fr/web/api/gamepad_api/using_the_gamepad_api/index.md @@ -4,38 +4,49 @@ slug: Web/API/Gamepad_API/Using_the_Gamepad_API translation_of: Web/API/Gamepad_API/Using_the_Gamepad_API original_slug: Web/Guide/API/Gamepad --- -<p>{{ SeeCompatTable() }}</p> - -<p>HTML5 a introduit plusieurs des composants nécessaires pour le développement de jeux vidéos riches et interactifs. Des technologies comme <code><canvas></code>, WebGL, <code><audio></code>, et <code><video></code>, ainsi que les implémentations JavaScript, ont mûri au point de supporter plusieurs fonctions autrefois réservées aux applications natives. L'API Gamepad est une manière pour les développeurs et <em><code>designers</code></em> d'accéder aux contrôleurs de jeux.</p> - -<div class="note"> - <p><strong>Note :</strong> Dans Firefox 29 et plus, l'API Gamepad est activée par défaut, tout comme pour les versions Nightly et Aurora. Depuis Firefox 24, l'API Gamepad était déjà disponible derrière une option dans les préférences. Il est possible de l'activer dans ces versions en ouvrant <code>about:config</code> et en activant <code>dom.gamepad.enabled</code>.</p> -</div> -<p>L'API Gamepad introduit de nouveaux évènements à l'objet {{ domxref("Window") }} pour lire l'état des contrôleurs. En plus de ces événements, l'API ajoute aussi un objet {{ domxref("Gamepad") }} que vous pouvez utiliser pour récupérer l'état d'un contrôleur connecté, et une méthode {{ domxref("navigator.getGamepads") }} que vous pouvez utiliser pour obtenir la liste des contrôleurs connus par la page.</p> -<h2 id="conntecting">Connexion au contrôleur</h2> -<p>Lorsqu'un nouveau contrôleur est connecté à l'ordinateur, la page active reçoit tout d'abord un événement {{ domxref("Window.gamepadconnected") }}. Si un contrôleur est déjà connecté lorsque la page termine de charger, l'événement {{ domxref("Window.gamepadconnected") }} est envoyé à la page active lorsque l'utilisateur appuie sur un bouton ou bouge un axe.</p> -<div> - <p>Dans Firefox, les contrôleurs ne sont rendus visibles à une page que lorsque l'utilisateur s'en sert alors que cette page est active. Cela permet d'éviter que les contrôleurs soient utilisés pour identifier l'utilisateur. Dès lors qu'un contrôleur a été utilisé, les autres contrôleurs connectés seront rendus visibles automatiquement.</p> -</div> -<p>Vous pouvez utiliser {{ domxref("Window.gamepadconnected") }} ainsi :</p> -<pre class="brush: js">window.addEventListener("gamepadconnected", function(e) { +{{ SeeCompatTable() }} + +HTML5 a introduit plusieurs des composants nécessaires pour le développement de jeux vidéos riches et interactifs. Des technologies comme `<canvas>`, WebGL, `<audio>`, et `<video>`, ainsi que les implémentations JavaScript, ont mûri au point de supporter plusieurs fonctions autrefois réservées aux applications natives. L'API Gamepad est une manière pour les développeurs et _`designers`_ d'accéder aux contrôleurs de jeux. + +> **Note :** Dans Firefox 29 et plus, l'API Gamepad est activée par défaut, tout comme pour les versions Nightly et Aurora. Depuis Firefox 24, l'API Gamepad était déjà disponible derrière une option dans les préférences. Il est possible de l'activer dans ces versions en ouvrant `about:config` et en activant `dom.gamepad.enabled`. + +L'API Gamepad introduit de nouveaux évènements à l'objet {{ domxref("Window") }} pour lire l'état des contrôleurs. En plus de ces événements, l'API ajoute aussi un objet {{ domxref("Gamepad") }} que vous pouvez utiliser pour récupérer l'état d'un contrôleur connecté, et une méthode {{ domxref("navigator.getGamepads") }} que vous pouvez utiliser pour obtenir la liste des contrôleurs connus par la page. + +## Connexion au contrôleur + +Lorsqu'un nouveau contrôleur est connecté à l'ordinateur, la page active reçoit tout d'abord un événement {{ domxref("Window.gamepadconnected") }}. Si un contrôleur est déjà connecté lorsque la page termine de charger, l'événement {{ domxref("Window.gamepadconnected") }} est envoyé à la page active lorsque l'utilisateur appuie sur un bouton ou bouge un axe. + +Dans Firefox, les contrôleurs ne sont rendus visibles à une page que lorsque l'utilisateur s'en sert alors que cette page est active. Cela permet d'éviter que les contrôleurs soient utilisés pour identifier l'utilisateur. Dès lors qu'un contrôleur a été utilisé, les autres contrôleurs connectés seront rendus visibles automatiquement. + +Vous pouvez utiliser {{ domxref("Window.gamepadconnected") }} ainsi : + +```js +window.addEventListener("gamepadconnected", function(e) { console.log("Contrôleur n°%d connecté : %s. %d boutons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); }); -</pre> -<p>Chaque contrôleur est associé à un identifiant unique, qui est disponible dans la propriété <code>gamepad</code> de l'événement.</p> -<div class="note"> - <p><strong>Note :</strong> À l'écriture de ces lignes, Chrome n'implémente pas les événements {{ domxref("Window.gamepadconnected") }} et {{ domxref("Window.gamepaddisconnected") }}. Vous devez utiliser {{ domxref("navigator.getGamepads") }} pour récupérer la liste des contrôleurs disponibles.</p> -</div> -<h2 id="disconnecting">Déconnexion du contrôleur</h2> -<p>Lorsqu'un contrôleur est déconnecté, et si la page avait déjà reçu des données de ce contrôleur auparavant (par exemple par l'événement {{ domxref("Window.gamepadconnected") }}), un second événement est envoyé à la fenêtre active : {{ domxref("Window.gamepaddisconnected") }}.</p> -<pre class="brush: js">window.addEventListener("gamepaddisconnected", function(e) { +``` + +Chaque contrôleur est associé à un identifiant unique, qui est disponible dans la propriété `gamepad` de l'événement. + +> **Note :** À l'écriture de ces lignes, Chrome n'implémente pas les événements {{ domxref("Window.gamepadconnected") }} et {{ domxref("Window.gamepaddisconnected") }}. Vous devez utiliser {{ domxref("navigator.getGamepads") }} pour récupérer la liste des contrôleurs disponibles. + +## Déconnexion du contrôleur + +Lorsqu'un contrôleur est déconnecté, et si la page avait déjà reçu des données de ce contrôleur auparavant (par exemple par l'événement {{ domxref("Window.gamepadconnected") }}), un second événement est envoyé à la fenêtre active : {{ domxref("Window.gamepaddisconnected") }}. + +```js +window.addEventListener("gamepaddisconnected", function(e) { console.log("Contrôleur n°%d déconnecté : %s", e.gamepad.index, e.gamepad.id); -});</pre> -<p>La propriété <code>index</code> sera unique à chaque périphérique connecté au système, même si plusieurs contrôleurs du même type sont utilisés. La propriété correspond également à l'indice du tableau retourné par {{ domxref("navigator.getGamepads") }}.</p> -<pre class="brush: js">var gamepads = {}; +}); +``` + +La propriété `index` sera unique à chaque périphérique connecté au système, même si plusieurs contrôleurs du même type sont utilisés. La propriété correspond également à l'indice du tableau retourné par {{ domxref("navigator.getGamepads") }}. + +```js +var gamepads = {}; function gamepadHandler(event, connecting) { var gamepad = event.gamepad; @@ -51,46 +62,53 @@ function gamepadHandler(event, connecting) { window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false); window.addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false); -</pre> -<p>Cet exemple montre également comment la propriété <code>gamepad</code> peut être conservée après que l'événement se soit terminé. Cette technique sera utilisée plus tard pour obtenir l'état du périphérique.</p> -<div> - [PAGE NON TRADUITE DEPUIS ICI...]</div> -<div> - </div> -<h2 id="querying">Querying the Gamepad object</h2> -<p>As you can see, the <strong>gamepad</strong> events discussed above include a <code>gamepad</code> property on the event object, which returns a {{ domxref("Gamepad") }} object. We can use this in order to determine which gamepad (i.e., its ID) had caused the event, since multiple gamepads might be connected at once. We can do much more with the {{ domxref("Gamepad") }} object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. Doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires.</p> -<p>Performing such checks tends to involve using the {{ domxref("Gamepad") }} object in conjunction with an animation loop (e.g., {{ domxref("requestAnimationFrame") }}), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads.</p> -<div class="note"> - <p><strong>Note :</strong> The Gamepad API also provides a function -- {{ domxref("Navigator.getGamepads") }}-- that returns a list of all devices currently visible to the webpage, an array of {{ domxref("Gamepad") }} objects. This can then be used to get the same information. For example, the first code example above you be rewritten as shown below:</p> -</div> -<pre class="brush: js">window.addEventListener("gamepadconnected", function(e) { +``` + +Cet exemple montre également comment la propriété `gamepad` peut être conservée après que l'événement se soit terminé. Cette technique sera utilisée plus tard pour obtenir l'état du périphérique. + +\[PAGE NON TRADUITE DEPUIS ICI...] + +## Querying the Gamepad object + +As you can see, the **gamepad** events discussed above include a `gamepad` property on the event object, which returns a {{ domxref("Gamepad") }} object. We can use this in order to determine which gamepad (i.e., its ID) had caused the event, since multiple gamepads might be connected at once. We can do much more with the {{ domxref("Gamepad") }} object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. Doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires. + +Performing such checks tends to involve using the {{ domxref("Gamepad") }} object in conjunction with an animation loop (e.g., {{ domxref("requestAnimationFrame") }}), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads. + +> **Note :** The Gamepad API also provides a function -- {{ domxref("Navigator.getGamepads") }}-- that returns a list of all devices currently visible to the webpage, an array of {{ domxref("Gamepad") }} objects. This can then be used to get the same information. For example, the first code example above you be rewritten as shown below: + +```js +window.addEventListener("gamepadconnected", function(e) { var gp = navigator.getGamepads()[e.gamepad.index]; console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length); -});</pre> -<p>The {{ domxref("Gamepad") }} object's properties are as follows:</p> -<ul> - <li><code>id</code>: A string containing some information about the controller. This is not strictly specified, but in Firefox it will contain three pieces of information separated by dashes (<code>-</code>): two 4-digit hexadecimal strings containing the USB vendor and product id of the controller, and the name of the controller as provided by the driver. This information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user.</li> - <li><code>index</code>: An integer that is unique for each gamepad currently connected to the system. This can be used to distinguish multiple controllers. Note that disconnecting a device and then connecting a new device may reuse the previous index.</li> - <li><code>mapping</code>: A string indicating whether the browser has remapped the controls on the device to a known layout. Currently there is only one supported known layout–the <a href="https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html#remapping">standard gamepad</a>. If the browser is able to map controls on the device to that layout the <code>mapping</code> property will be set to the string <code>standard</code>.</li> - <li><code>connected</code>: A boolean indicating whether the gamepad is still connected to the system. If this is so the value is <code>True</code>; if not, it is <code>False</code>.</li> - <li><code>buttons</code>: An array of {{ domxref("GamepadButton") }} objects representing the buttons present on the device. Each {{ domxref("GamepadButton") }} has a <code>pressed</code> and a <code>value</code> property: - <ul> - <li>The <code>pressed</code> property is a boolean indicating whether the button is currently pressed (<code>true</code>) or unpressed (<code>false</code>).</li> - <li>The <code>value</code> property is a floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0..1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed.</li> - </ul> - </li> - <li><code>axes</code>: An array representing the controls with axes present on the device (e.g. analog thumb sticks). Each entry in the array is a floating point value in the range -1.0 - 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0).</li> - <li><code>timestamp</code>: This returns a {{ domxref("DOMHighResTimeStamp") }} representing the last time the data for this gamepad was updated, allowing developers to determine if the <code>axes</code> and <code>button</code> data have been updated from the hardware. The value must be relative to the <code>navigationStart</code> attribute of the {{ domxref("PerformanceTiming") }} interface. Values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. Note that this property is not currently supported in Firefox.</li> -</ul> -<div class="note"> - <p><strong>Note :</strong> The Gamepad object is available on the {{ domxref("Window.gamepadconnected") }} event rather than the {{ domxref("Window") }} object itself, for security reasons. Once we have a reference to it, we can query its properties for information about the current state of the gamepad. Behind the scenes, this object will be updated every time the gamepad's state changes.</p> -</div> -<h3 id="Using_button_information">Using button information</h3> -<p>Let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad. You can <a href="http://chrisdavidmills.github.io/gamepad-buttons/">view the demo live</a>, and <a href="https://github.com/chrisdavidmills/gamepad-buttons/tree/master">find the source code</a> on Github.</p> -<p>To start with, we declare some variables: The <code>gamepadInfo</code> paragraph that the connection info is written into, the <code>ball</code> that we want to move, the <code>start</code> variable that acts as the ID for <code>requestAnimation Frame</code>, the <code>a</code> and <code>b</code> variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the {{ domxref("requestAnimationFrame") }} and {{ domxref("cancelRequestAnimationFrame") }} cross browser forks.</p> -<pre class="brush: js">var gamepadInfo = document.getElementById("gamepad-info"); +}); +``` + +The {{ domxref("Gamepad") }} object's properties are as follows: + +- `id`: A string containing some information about the controller. This is not strictly specified, but in Firefox it will contain three pieces of information separated by dashes (`-`): two 4-digit hexadecimal strings containing the USB vendor and product id of the controller, and the name of the controller as provided by the driver. This information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. +- `index`: An integer that is unique for each gamepad currently connected to the system. This can be used to distinguish multiple controllers. Note that disconnecting a device and then connecting a new device may reuse the previous index. +- `mapping`: A string indicating whether the browser has remapped the controls on the device to a known layout. Currently there is only one supported known layout–the [standard gamepad](https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html#remapping). If the browser is able to map controls on the device to that layout the `mapping` property will be set to the string `standard`. +- `connected`: A boolean indicating whether the gamepad is still connected to the system. If this is so the value is `True`; if not, it is `False`. +- `buttons`: An array of {{ domxref("GamepadButton") }} objects representing the buttons present on the device. Each {{ domxref("GamepadButton") }} has a `pressed` and a `value` property: + + - The `pressed` property is a boolean indicating whether the button is currently pressed (`true`) or unpressed (`false`). + - The `value` property is a floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0..1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. + +- `axes`: An array representing the controls with axes present on the device (e.g. analog thumb sticks). Each entry in the array is a floating point value in the range -1.0 - 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). +- `timestamp`: This returns a {{ domxref("DOMHighResTimeStamp") }} representing the last time the data for this gamepad was updated, allowing developers to determine if the `axes` and `button` data have been updated from the hardware. The value must be relative to the `navigationStart` attribute of the {{ domxref("PerformanceTiming") }} interface. Values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. Note that this property is not currently supported in Firefox. + +> **Note :** The Gamepad object is available on the {{ domxref("Window.gamepadconnected") }} event rather than the {{ domxref("Window") }} object itself, for security reasons. Once we have a reference to it, we can query its properties for information about the current state of the gamepad. Behind the scenes, this object will be updated every time the gamepad's state changes. + +### Using button information + +Let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad. You can [view the demo live](http://chrisdavidmills.github.io/gamepad-buttons/), and [find the source code](https://github.com/chrisdavidmills/gamepad-buttons/tree/master) on Github. + +To start with, we declare some variables: The `gamepadInfo` paragraph that the connection info is written into, the `ball` that we want to move, the `start` variable that acts as the ID for `requestAnimation Frame`, the `a` and `b` variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the {{ domxref("requestAnimationFrame") }} and {{ domxref("cancelRequestAnimationFrame") }} cross browser forks. + +```js +var gamepadInfo = document.getElementById("gamepad-info"); var ball = document.getElementById("ball"); var start; var a = 0; @@ -102,29 +120,41 @@ var rAF = window.mozRequestAnimationFrame || var rAFStop = window.mozCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || - window.cancelRequestAnimationFrame;</pre> -<p>Next we use the {{ domxref("Window.gamepadconnected") }} event to check for a gamepad being connected. When one is connected, we grab the gamepad using {{ domxref("Navigator.getGamepads") }}<code>[0]</code>, print information about the gamepad into our gamepad info <code>div</code>, and fire the <code>gameLoop()</code> function that starts the whole ball movement process up.</p> -<pre class="brush: js">window.addEventListener("gamepadconnected", function(e) { + window.cancelRequestAnimationFrame; +``` + +Next we use the {{ domxref("Window.gamepadconnected") }} event to check for a gamepad being connected. When one is connected, we grab the gamepad using {{ domxref("Navigator.getGamepads") }}`[0]`, print information about the gamepad into our gamepad info `div`, and fire the `gameLoop()` function that starts the whole ball movement process up. + +```js +window.addEventListener("gamepadconnected", function(e) { var gp = navigator.getGamepads()[e.gamepad.index]; gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes."; gameLoop(); -});</pre> -<p>Now we use the {{ domxref("Window.gamepaddisconnected") }} event to check if the gamepad is disconnected again. If so, we stop the {{ domxref("requestAnimationFrame") }} loop (see below) and revert the gamepad information back to what it was originally.</p> -<pre class="brush: js">window.addEventListener("gamepaddisconnected", function(e) { +}); +``` + +Now we use the {{ domxref("Window.gamepaddisconnected") }} event to check if the gamepad is disconnected again. If so, we stop the {{ domxref("requestAnimationFrame") }} loop (see below) and revert the gamepad information back to what it was originally. + +```js +window.addEventListener("gamepaddisconnected", function(e) { gamepadInfo.innerHTML = "Waiting for gamepad."; rAFStop(start); -});</pre> -<p>Chrome does things differently here. Instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in Chrome you have to keep polling it and then only use the {{ domxref("Gamepad") }} object in code when it is available. We have done this below using {{ domxref("Window.setInterval") }}; once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using {{ domxref("Window.clearInterval") }}. Note that in older versions of Chrome {{ domxref("Navigator.getGamepads") }} is implemented with a <code>webkit</code> prefix. We attempt to detect and handle both the prefixed version and the standard version of the function for backwards-compatibility.</p> -<pre class="brush: js">if(!('GamepadEvent' in window)) { +}); +``` + +Chrome does things differently here. Instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in Chrome you have to keep polling it and then only use the {{ domxref("Gamepad") }} object in code when it is available. We have done this below using {{ domxref("Window.setInterval") }}; once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using {{ domxref("Window.clearInterval") }}. Note that in older versions of Chrome {{ domxref("Navigator.getGamepads") }} is implemented with a `webkit` prefix. We attempt to detect and handle both the prefixed version and the standard version of the function for backwards-compatibility. + +```js +if(!('GamepadEvent' in window)) { // No gamepad events available, poll instead. var interval = setInterval(pollGamepads, 500); } function pollGamepads() { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); - for (var i = 0; i < gamepads.length; i++) { + for (var i = 0; i < gamepads.length; i++) { var gp = gamepads[i]; if(gp) { gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes."; @@ -132,10 +162,15 @@ function pollGamepads() { clearInterval(interval); } } -}</pre> -<p>Now on to the main game loop. In each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the <code>a</code> and <code>b</code> movement variables appropriately, then update the {{ cssxref("left") }} and {{ cssxref("top") }} properties, changing their values to the current values of <code>a</code> and <code>b</code> respectively. This has the effect of moving the ball around the screen. In current versions of Chrome (version 34 as of this writing) the button values are stored as an array of double values, instead of {{ domxref("GamepadButton") }} objects. This is fixed in development versions.</p> -<p>After all this is done, we use our <code>rAF</code> variable to request the next animation frame, running <code>gameLoop()</code> again.</p> -<pre class="brush: js">function buttonPressed(b) { +} +``` + +Now on to the main game loop. In each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the `a` and `b` movement variables appropriately, then update the {{ cssxref("left") }} and {{ cssxref("top") }} properties, changing their values to the current values of `a` and `b` respectively. This has the effect of moving the ball around the screen. In current versions of Chrome (version 34 as of this writing) the button values are stored as an array of double values, instead of {{ domxref("GamepadButton") }} objects. This is fixed in development versions. + +After all this is done, we use our `rAF` variable to request the next animation frame, running `gameLoop()` again. + +```js +function buttonPressed(b) { if (typeof(b) == "object") { return b.pressed; } @@ -163,12 +198,19 @@ function gameLoop() { ball.style.top = b*2 + "px"; var start = rAF(gameLoop); -};</pre> -<h3 id="Using_axes_information">Using axes information</h3> -<p><strong>TBD (basically the same, except using axes[i] rather than button[i].value for both Firefox and Chrome.)</strong></p> -<h2 id="Complete_example_Displaying_gamepad_state">Complete example: Displaying gamepad state</h2> -<p>This example shows how to use the {{ domxref("Gamepad") }} object, as well as the {{ domxref("Window.gamepadconnected") }} and {{ domxref("Window.gamepaddisconnected") }} events in order to display the state of all gamepads connected to the system. You can find a <a href="http://luser.github.io/gamepadtest/">working demo</a> and look at the <a href="https://github.com/luser/gamepadtest">full source code</a> on Github.</p> -<pre class="brush: js">var haveEvents = 'GamepadEvent' in window; +}; +``` + +### Using axes information + +**TBD (basically the same, except using axes\[i] rather than button\[i].value for both Firefox and Chrome.)** + +## Complete example: Displaying gamepad state + +This example shows how to use the {{ domxref("Gamepad") }} object, as well as the {{ domxref("Window.gamepadconnected") }} and {{ domxref("Window.gamepaddisconnected") }} events in order to display the state of all gamepads connected to the system. You can find a [working demo](http://luser.github.io/gamepadtest/) and look at the [full source code](https://github.com/luser/gamepadtest) on Github. + +```js +var haveEvents = 'GamepadEvent' in window; var controllers = {}; var rAF = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || @@ -185,7 +227,7 @@ function addgamepad(gamepad) { d.appendChild(t); var b = document.createElement("div"); b.className = "buttons"; - for (var i=0; i<gamepad.buttons.length; i++) { + for (var i=0; i<gamepad.buttons.length; i++) { var e = document.createElement("span"); e.className = "button"; //e.id = "b" + i; @@ -195,7 +237,7 @@ function addgamepad(gamepad) { d.appendChild(b); var a = document.createElement("div"); a.className = "axes"; - for (var i=0; i<gamepad.axes.length; i++) { + for (var i=0; i<gamepad.axes.length; i++) { var e = document.createElement("progress"); e.className = "axis"; //e.id = "a" + i; @@ -228,7 +270,7 @@ function updateStatus() { var controller = controllers[j]; var d = document.getElementById("controller" + j); var buttons = d.getElementsByClassName("button"); - for (var i=0; i<controller.buttons.length; i++) { + for (var i=0; i<controller.buttons.length; i++) { var b = buttons[i]; var val = controller.buttons[i]; var pressed = val == 1.0; @@ -246,7 +288,7 @@ function updateStatus() { } var axes = d.getElementsByClassName("axis"); - for (var i=0; i<controller.axes.length; i++) { + for (var i=0; i<controller.axes.length; i++) { var a = axes[i]; a.innerHTML = i + ": " + controller.axes[i].toFixed(4); a.setAttribute("value", controller.axes[i] + 1); @@ -257,7 +299,7 @@ function updateStatus() { function scangamepads() { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []); - for (var i = 0; i < gamepads.length; i++) { + for (var i = 0; i < gamepads.length; i++) { if (gamepads[i]) { if (!(gamepads[i].index in controllers)) { addgamepad(gamepads[i]); @@ -272,11 +314,13 @@ window.addEventListener("gamepadconnected", connecthandler); window.addEventListener("gamepaddisconnected", disconnecthandler); if (!haveEvents) { setInterval(scangamepads, 500); -}</pre> -<h2 id="Specifications">Specifications</h2> -<p>{{page("/en-US/docs/Gamepad","Specifications")}}</p> -<h2 id="Browser_compatibility">Browser compatibility</h2> -<p>{{page("/en-US/docs/Gamepad","Browser_compatibility")}}</p> -<p> </p> -<p> </p> -<p> </p> +} +``` + +## Specifications + +{{page("/en-US/docs/Gamepad","Specifications")}} + +## Browser compatibility + +{{page("/en-US/docs/Gamepad","Browser_compatibility")}} |