HTML and CSS Reference
In-Depth Information
Axis Events
You have the buttons covered, but what about the analog sticks? They are different from buttons, as buttons have only
two possible values, 1 or 0, as they are either pressed or not. It's more complicated, however, with analog sticks as they
can have different pressure applied at different angles. For example, if you move your left analog stick halfway to the
bottom-left corner, you'll end up with the top-down axis holding a value of 0.5 and the left-right one with a value of
-0.5. Let's see how to handle this.
window.addEventListener("gamepadaxismove", function(e){
gamepadAPI.axisPressed(e);
});
axisPressed: function(event) {
var axis = event.axis,
value = event.value;
console.log("Axis: "+axis+", value: "+value+".");
}
First comes the event listener for gamepadaxismove , and then the function that is executed. You just take the axis
that was moved by the player on the device and its value. This can be applied to any game logic, for example steering a
tank or other vehicle.
Axis Threshold
Be aware that analog sticks are not perfect—some of them will not return to 0.0 states, whether it's because of the
materials used or simply a problem of a little dirt. They can stay with 0.02 values, and it's important to take that into
account. For example, you can move your tank's turret right only when the value from the left-right axis exceeds 0.5, so
it's between 0.5 and 1. The values from 0 to 0.5 will be ignored and the turret will be moved only when you exceed the
0.5 threshold.
Gamepad Object
It might be difficult to put all of a game's logic inside a single function responsible for managing the buttons.
Fortunately, there is another solution: querying the gamepad object directly. I already covered this at the beginning of
the implementation part, remember?
window.addEventListener("gamepadconnected", function(e) {
var controller = e.gamepad;
gamepadAPI.controllers[e.gamepad.index] = controller;
gamepadAPI.active = true;
});
Earlier, I said that you can extract any data from the gamepad object and do whatever you want with it , so let's do
it! You will put the code responsible for querying the gamepad object for any buttons that are pressed in a game loop.
That way, you will have the actual data about whether the button is pressed or not in every frame, or what was the
exact value of the axis used. Here's the code used in the main menu of the game Hungry Fridge , which was put into the
update loop to allow the player to start the game on a gamepad button press:
if(gamepadAPI.active) {
for(c in gamepadAPI.controllers) {
var controller = gamepadAPI.controllers[c];
 
Search WWH ::




Custom Search