Created
June 21, 2016 21:14
-
-
Save connerbrooks/631fe9263521c0722ba30bba2fa17b23 to your computer and use it in GitHub Desktop.
Three.js ViveController with button events.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
THREE.ViveController = function ( id ) { | |
THREE.Object3D.call( this ); | |
this.matrixAutoUpdate = false; | |
this.standingMatrix = new THREE.Matrix4(); | |
var scope = this; | |
this.gamepad; | |
this.buttons; | |
window.addEventListener('gamepadButtonClicked_' + id, function(e) { | |
console.log('Button Event: ', e); | |
}) | |
window.addEventListener('gamepadButtonReleased_' + id, function(e) { | |
console.log('Button Event: ', e); | |
}) | |
function update() { | |
requestAnimationFrame( update ); | |
var gamepad = navigator.getGamepads()[ id ]; | |
if (!scope.buttons) { | |
scope.buttons = JSON.parse(JSON.stringify(gamepad.buttons)); | |
} | |
if ( gamepad !== undefined && gamepad.pose !== null ) { | |
var pose = gamepad.pose; | |
scope.position.fromArray( pose.position ); | |
scope.quaternion.fromArray( pose.orientation ); | |
scope.matrix.compose( scope.position, scope.quaternion, scope.scale ); | |
scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix ); | |
scope.matrixWorldNeedsUpdate = true; | |
scope.visible = true; | |
for (var j = 0; j < gamepad.buttons.length; ++j) { | |
if (gamepad.buttons[j].pressed && !scope.buttons[j].isHeld) { | |
console.log("button " + j + " pressed"); | |
scope.buttons[j].isHeld = true; | |
var pressedEvent = new CustomEvent('gamepadButtonClicked_' + id, { | |
detail: scope.buttons[j], | |
id: j | |
}); | |
window.dispatchEvent(pressedEvent); | |
} | |
if(!gamepad.buttons[j].pressed && scope.buttons[j].isHeld) { | |
scope.buttons[j].isHeld = false; | |
console.log("button " + j + " released"); | |
var releasedEvent = new CustomEvent('gamepadButtonReleased_' + id, { | |
detail: scope.buttons[j], | |
id: j | |
}); | |
window.dispatchEvent(releasedEvent); | |
} | |
} | |
} else { | |
scope.visible = false; | |
} | |
} | |
update(); | |
}; | |
THREE.ViveController.prototype = Object.create( THREE.Object3D.prototype ); | |
THREE.ViveController.prototype.constructor = THREE.ViveController; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment