Object3D Player WebXR
by Cody Bennett
CSS
body {
margin: 0;
}
canvas {
display: block;
}
JavaScript
import * as THREE from 'https://unpkg.com/three/build/three.module.js';
import { VRButton } from 'https://unpkg.com/three/examples/jsm/webxr/VRButton.js';
import { XRControllerModelFactory } from 'https://unpkg.com/three/examples/jsm/webxr/XRControllerModelFactory.js';
import { XRHandModelFactory } from 'https://unpkg.com/three/examples/jsm/webxr/XRHandModelFactory.js';
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(2);
renderer.xr.enabled = true;
document.body.appendChild(renderer.domElement);
document.body.appendChild(VRButton.createButton(renderer));
const player = new THREE.Object3D();
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 10);
camera.position.set(0, 1.6, 3);
player.add(camera);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x808080);
const floorGeometry = new THREE.PlaneBufferGeometry(4, 4);
const floorMaterial = new THREE.MeshStandardMaterial({ color: 0xeeeeee });
const floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.rotation.x = -Math.PI / 2;
scene.add(floor);
// Add Controllers
const controller1 = renderer.xr.getController(0);
player.add(controller1);
const controller2 = renderer.xr.getController(1);
player.add(controller2);
// Create controller and hand models
const controllerModelFactory = new XRControllerModelFactory();
const handModelFactory = new XRHandModelFactory();
// Add Joysticks
const controllerGrip1 = renderer.xr.getControllerGrip(0);
controllerGrip1.add( controllerModelFactory.createControllerModel(controllerGrip1));
player.add(controllerGrip1);
const controllerGrip2 = renderer.xr.getControllerGrip(1);
controllerGrip2.add( controllerModelFactory.createControllerModel(controllerGrip2));
player.add(controllerGrip2);
// Add Hands
const hand1 =...