Package Exports
- spatial-controls
Readme
Spatial Controls
A 3D movement controller that supports multiple control modes and configurable input settings.
Installation
This library requires the peer dependency three.
npm install three spatial-controls
Usage
import { Quaternion, Vector3 } from "three";
import { SpatialControls } from "spatial-controls";
const position = new Vector3();
const quaternion = new Quaternion();
const domElement = document.getElementById("viewport");
const controls = new SpatialControls(position, quaternion, domElement);
requestAnimationFrame(function render(timestamp) {
requestAnimationFrame(render);
controls.update(timestamp);
});
Position, Target and Quaternion
// First person: Sets the position.
// Third person: Sets the target and adjusts the position.
controls.moveTo(x, y, z);
controls.moveTo(point);
// Sets or replaces the position and looks at the target.
controls.setPosition(x, y, z);
controls.setPosition(otherPosition);
// Sets or replaces the target and updates the quaternion.
controls.setTarget(x, y, z);
controls.setTarget(otherTarget);
// Same as setTarget() but doesn't replace the target.
controls.lookAt(x, y, z);
controls.lookAt(target);
Settings
Configuration
import { Action, ControlMode, KeyCode } from "spatial-controls";
const settings = controls.settings;
settings.general.setMode(ControlMode.THIRD_PERSON);
settings.rotation.setSensitivity(2.2);
settings.rotation.setDamping(0.05);
settings.translation.setSensitivity(0.25);
settings.translation.setDamping(0.1);
settings.zoom.setRange(0.25, 3.0);
settings.zoom.setDamping(0.1);
const keyBindings = settings.keyBindings;
keyBindings.delete(KeyCode.X);
keyBindings.set(KeyCode.V, Action.MOVE_DOWN);
Saving and Loading
// JSON round-trip.
const json = JSON.stringify(settings);
settings.fromJSON(json);
// Via local storage.
localStorage.setItem("spatial-controls", JSON.stringify(settings));
settings.fromJSON(localStorage.getItem("spatial-controls"));
// Save as JSON file.
const settingsURL = URL.createObjectURL(settings.toBlob());
const a = document.createElement("a");
a.setAttribute("href", settingsURL);
a.setAttribute("download", "spatial-controls.json");
a.click();
URL.revokeObjectURL(settingsURL);
// Load from JSON file.
fetch("./spatial-controls.json")
.then(response => response.text())
.then(data => settings.fromJSON(data))
.catch(e => console.error(e));
Contributing
Please refer to the contribution guidelines for details.