Exploring the functionalities of PointerLockControls, incorporating WASD controls, and experimenting with Three.js

Forgive me if this is a beginner question, but I've noticed that in the official three.js examples, the PointerLockControls.js allows for mouse pointer lock and WASD key navigation.

I have successfully locked the mouse pointer, but I am having trouble getting the WASD keys to function.

Could it be that I'm not using the right .js script to begin with?

I'm still quite new at this, but I believe my file is almost there! Any assistance would be greatly appreciated.

Here's the code I'm working with:


import * as THREE from './three.js-master/build/three.module.js'
import {GLTFLoader} from './three.js-master/examples/jsm/loaders/GLTFLoader.js'
import {PointerLockControls} from './three.js-master/examples/jsm/controls/PointerLockControls.js'

if (typeof window !== 'undefined' && typeof window.THREE === 'object') {
  window.THREE.SimpleFPControls = SimpleFPControls;
}

const canvas = document.querySelector('.webgl')
const scene = new THREE.Scene()

const loader = new GLTFLoader
loader.load('assets/untitled.glb', function(glb){
    console.log(glb)
    const root = glb.scene;
    root.scale.set(0.01,0.01,0.01)

    scene.add(root);
}, function(xhr){
    console.log((xhr.loaded/xhr.total * 100) + "% loaded")
}, function(error){
    console.log('An error occured')
})

const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(0,0,2)
scene.add(light)

// Commented out geometry and material for demonstration purposes

//BOILER PLATE CODE
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

const camera = new THREE.PerspectiveCamera(75, sizes.width/sizes.height, 0.1, 100)
camera.position.set(0,1,10)
camera.lookAt(0, 0, 0);
scene.add(camera)

let fpsControls = new PointerLockControls(camera, document.body);

document.body.addEventListener('click', function () {
    fpsControls.lock();
}, false);

const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})

renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
renderer.shadowMap.enabled = true
renderer.outputEncoding = true
document.body.appendChild(renderer.domElement)

function animate(){
    requestAnimationFrame(animate)
    renderer.render(scene, camera)
}

const controls = new PointerLockControls(camera, document.body);

animate()

Answer №1

PointerLockControls primarily focuses on managing event listeners for pointerlockchange, pointerlockerror, and mousemove. Through this, it handles mouse capturing and translates mouse movements to camera rotation.

Interestingly, this class does not include event listeners for key inputs. In examining the code of the official example, you will notice that these key events are dealt with at the application level.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to conceal a div using jQuery when the video source is missing

If there is no source in the video, I want to hide the video_wrapper class <div class="video_wrapper" style="width: 100%; height: 100%; display: none;"> <video id="df-video" playsinline="" webkit-playsinline="" style="height: 100%; width: 100%; ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

The dropdown value is limited to storing data up to the specified space

I am facing an issue with storing data selected from the second dropdown in my form. The first dropdown is for selecting the Brand Name of a car, and the second dropdown retrieves data from the database based on the brand name selected. I have used a div t ...

What is the best way to retrieve the name of a dynamic form in a Controller

How can I retrieve the dynamic form name in my controller? See below for the code snippet: HTML <form name="{{myForm}}" novalidate> <input type="text" ng-model="username" name="username" required/> <span ng-show="(submit & ...

redux - managing asynchronous storage using key-value pairs

Utilizing associative arrays with redux and storing them in async storage for later retrieval is my current challenge. When using redux, I am able to quickly access the values and efficiently map the content into cards in my react native app. However, aft ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

Implementing a callback in the app.get function within Node.js: A step-by-step guide

I have a fully functioning website and now I am looking to add some logic and data analysis to it. Below is the code snippet for rendering my /data page: app.get("/data", (req, res) => { const sql = "SELECT * FROM MyMoods"; cons ...

What is the best way to delete an added element once a DIV has been toggled with JQuery?

I'm facing an issue where I need to add an element to a DIV that has a toggle function. However, every time I click the toggle again after adding the element, the same element is appended once more, resulting in duplicate elements. Upon observation, ...

Troubleshooting problem: Unable to restrict table selections - issue with Material UI table in React

I seem to be overlooking the simple solution here. Currently, I have a ternary on my table. If the length of the selected array is greater than a certain number, a table with disabled checkboxes is rendered. I also implement a different handleClick functio ...

Steps to stop POST requests sent via AJAX (acquired through Firebug)

Is there any way to protect against users spamming a post request? Consider a scenario where a form is submitted through an Ajax post. I've observed that the post request can be duplicated by simply right clicking on it and choosing "open in a new tab ...

Comparison of element state prior to and post editing (with contentEditable)

Exploring how elements within a div can be monitored for changes made by the user (thanks to contentEditable), I created a sample page with the following setup: before_html = $("#example_div").children(); $("#differences_button").on("click", ...

Developing dynamic forms within arrays using AngularJS

Hey there! I've got a scenario where I have an array of people in my dynamic application. Each person, such as James, Bob, and Walter, has their own set of data that needs to be filled out using simple directives. $scope.users = [ { name: ...

Using PHP variables in JavaScript fetched through AJAX loading

I am currently attempting to retrieve a PHP variable from another page using AJAX in JavaScript, but it is not displaying any alerts. This is the PHP code for 'getposY': <?php include"connectdatabase.php"; $posYquery=mysql_query("Select posY ...

Is there a specific reason why react-helmet does not automatically update the og meta tag?

I am currently working on generating dynamic og. Specifically, I have a detailed page featuring news on my website. When sharing a link to this page, it should generate the og data. Below is an excerpt of my code: <Helmet> <title>{info &a ...

Angular Bootstrap uibModal is failing to resolve attributes

Issue with Roles in AngularJS Bootstrap uiModel var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', size: 100, resolve: { roles: f ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

Struggling to generate package using manifoldjs

Excited to dive into the new tool called ManifoldJS introduced by Microsoft at Build 2015, I'm facing some challenges. My website is up and running as a basic HTML- and JS-based app using Angular and TypeScript. I've even created a manifest.json ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

Performing asynchronous ajax calls with jQuery

Here is some code I have that involves a list and making an ajax call for each element in the list: util.testMethod = function(list) { var map = new Map(); list.forEach(function(data) { $.ajax({ ...

Unable to generate a select element using the JSON data retrieved from an Ajax request

After making an AJAX call to fetch some JSON objects, I successfully retrieve them. However, I encountered an issue while trying to generate a select element from the returned JSON - it doesn't seem to create one. This is what my JavaScript looks lik ...