babylon.gamepadCamera.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. module BABYLON {
  2. // We're mainly based on the logic defined into the FreeCamera code
  3. export class GamepadCamera extends FreeCamera {
  4. private _gamepad: BABYLON.Gamepad;
  5. private _gamepads: BABYLON.Gamepads;
  6. public angularSensibility = 200;
  7. public moveSensibility = 75;
  8. constructor(name: string, position: Vector3, scene: Scene) {
  9. super(name, position, scene);
  10. this._gamepads = new BABYLON.Gamepads((gamepad: BABYLON.Gamepad) => { this._onNewGameConnected(gamepad); });
  11. }
  12. private _onNewGameConnected(gamepad: BABYLON.Gamepad) {
  13. // Only the first gamepad can control the camera
  14. if (gamepad.index === 0) {
  15. this._gamepad = gamepad;
  16. }
  17. }
  18. public _checkInputs(): void {
  19. if (!this._gamepad) {
  20. return;
  21. }
  22. var LSValues = this._gamepad.leftStick;
  23. var normalizedLX = LSValues.x / this.moveSensibility;
  24. var normalizedLY = LSValues.y / this.moveSensibility;
  25. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27. var RSValues = this._gamepad.rightStick;
  28. var normalizedRX = RSValues.x / this.angularSensibility;
  29. var normalizedRY = RSValues.y / this.angularSensibility;
  30. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  31. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;;
  32. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  34. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  35. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  36. }
  37. public dispose(): void {
  38. this._gamepads.dispose();
  39. super.dispose();
  40. }
  41. }
  42. }