Tuesday, November 13, 2007

Question: How can I vibrate an Xbox 360 controller?

Answer: Vibrating an Xbox 360 controller is actually quite simple. All you need to do is call the SetVibration method of the static GamePad class.

To vibrate a controller, you don’t actually need a GamePadState to work with because all you have to do is call GamePad.SetVibration(…). For our sake though, we will create a GamePadState just so that we can check if certain buttons are down and then vibrate the controller respectively. Create a GamePadState at the top of the Update method.

//The GamePad to check for input from.
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);

Now, for a simple effect, whenever you are pressing the A button, the left motor of the controller vibrates and whenever you are pressing the B button, the right motor of the controller vibrates. To do this, place this code also into the Update method.

//Create two variables to keep track of the rotation values of the

//motors.
float leftMotorVibration = 0;
float rightMotorVibration = 0;

//If A is pressed, vibrate the left motor.
if (gamePad.Buttons.A == ButtonState.Pressed)
{
leftMotorVibration = 1;
}
else
{
leftMotorVibration = 0;
}
//If B is pressed, vibrate the right motor.
if (gamePad.Buttons.B == ButtonState.Pressed)
{
rightMotorVibration = 1;
}
else
{
rightMotorVibration = 0;
}

//Finally, vibrate the motors based on their individual values.
GamePad.SetVibration(PlayerIndex.One, leftMotorVibration,
rightMotorVibration);

First we create two simple floats to keep track of the vibration value of the motors. After that we check for input. Note that we have to check if the buttons are not pressed along with if they are pressed. This is because, if the buttons were pressed and then were released, nothing ever sets the vibration back to zero. Finally, after checking for input, we call the SetVibration method of the GamePad class. The first parameter specifies the player controller to vibrate which for us was Player 1. The second and third parameters specify the amount to rotate the motors by. For us we passed in leftMotorVibration and rightMotorVibration.

If you run the project now and press A or B, Player 1’s game controller should vibrate accordingly.

No comments: