Skip to content

Instantly share code, notes, and snippets.

@NSTCG
Last active September 12, 2023 14:45
Show Gist options
  • Save NSTCG/313ef5ae1c2208e645607a0075b78917 to your computer and use it in GitHub Desktop.
Save NSTCG/313ef5ae1c2208e645607a0075b78917 to your computer and use it in GitHub Desktop.
a component to change fov ( for pc ) on runtime with scroll
import {Component, Property, ViewComponent} from "@wonderlandengine/api";
/**
* scroll-fov
*/
export class ScrollFov extends Component {
static TypeName = "scroll-fov";
/* Properties that are configurable in the editor */
static Properties = {
sensitivity: Property.float(0.01),
fovUpperLimit: Property.float(120),
fovLowerLimit: Property.float(20),
};
start() {
this.addScrollListener();
}
addScrollListener() {
// Get the ViewComponent and sensitivity from properties
const viewComponent = this.object.getComponent(ViewComponent);
const sensitivity = this.sensitivity;
// Define a function to handle the scroll event
const handleScroll = (event) => {
// Check if the event is a wheel event (mouse scroll)
if (event.type === "wheel") {
// Prevent the default scroll behavior
event.preventDefault();
// Calculate the change in FOV based on the scroll sensitivity
const delta = event.deltaY * sensitivity;
// Calculate the new FOV value after applying the delta
const newFov = viewComponent.fov + delta;
// Ensure FOV stays within the upper and lower limits
const clampedFov = Math.min(
Math.max(newFov, this.fovLowerLimit),
this.fovUpperLimit,
);
// Modify the FOV
viewComponent.fov = clampedFov;
}
};
// Add the scroll event listener to the document or a specific element if needed
document.addEventListener("wheel", handleScroll, {passive: false});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment