domingo, 16 de setembro de 2012

Xbox 360 Joystick Controller + Unity

A few weeks ago I acquired a Xbox 360 joystick controller for Windows and, although my initial objective was to play with it (something I did, of course), my developer's mind did not allow the controller to remain in my desk without becoming part of my studies/experiments with Unity.

I configured Bitz to work with the joystick besides the keyboard and mouse. And with some quick changes I adapted Unity's script, MouseOrbit.js to take the the controller's input. The result can be seen in the video below:

So here's a short explanation of how to set Unity to receive the Xbox 360 controller for Windows.

To manage the user's input configurations Unity has a resource called Input Manager (at Edit > Project Settings > Input), with it it is possible to create, remove or edit the patterns recognized by the program, that by default are four: Keyboard or mouse button, mouse movement, joystick axis, and window movement. Every time the user causes one of those actions the Input Manager recognizes and processes the information, making it easier to be acessible through scripting.

In the simplest form, the user's input information are interpreted according to a code (KeyCode) attributed to each key or button pressed. For the axes (float type variables that go from -1 to 1 according to the intensity a button is pressed), Unity offers a list of all the available ones, about ten. While KeyCodes can be accessed by scripts directly through the Input class functions, to manage to get the return of the information generated by an axis it is necessary to first set it up on the Input Manager.

The KeyCodes reserved to controller buttons have the following format : "KeyCode.JoystickButton" followed by the number of the button. Here's a little map with the default number for each joystick button in Windows :D (if you use Mac, click here)

To set a new axis all you have to do is increase the parameter "Size" on Input Manager (Axes > Size). By doing it a new configurable axis will be generated. Having defined it's variables, like in the examples bellow, it is now possible to acess it using the attributed name:

In the example shown I have two new fully acessible axis which interact with the function Input.GetAxis(string axisName), which in that case would be Input.GetAxis("Right Analog X") and Input.GetAxis("Right Analog Y").

That way it is possible to program resources triggered by Xbox Joystick's axis and buttons and with a little effort it is also possible to adapt Unity's pre-made scripts to use the controller's axis, like MouseOrbit.js in Bitz demo.

Any doubt, comment, suggestion and/or etc, feel free to get in touch. :)

P.S: AnimationExporter demonstration, made by a college friend. :D
P.S.2: Bob's fanart!

Nenhum comentário:

Postar um comentário