`How can PointerLockControls be utilized to mimic third-person controls?`

Currently, my goal is to develop a third-person game similar to the one showcased here using three.js.

The code snippet from the above demonstration looks like this -

let anchor = new THREE.Object3D()
// anchor = character
anchor.position.y = 10

// In between, a perspective camera is initialized

anchor.add(camera) // Attaches camera to Anchor
controls = new PointerLockControls(anchor, container)

Now, in another project, I am working on replicating the third-person control functionality utilizing PointerLockControls and aiming to have the screen orbit around the character rather than the camera, as seen here.

The code I have written for the second demo so far is as follows:

//At some point, a perspective camera is established

camera.position.set(4, 4, 0)
const webglContainer = document.getElementById('webgl-container')

if (webglContainer) {
    const controls = new PointerLockControls(camera, webglContainer)

    scene.add(controls.getObject())

    webglContainer.addEventListener('click', () => {
        controls.lock()
    })
}

In the first example, the PointerLockControls class accepts Object3D since it's an older version of three.js. However, for the current version, it requires the camera as its constructor argument.

I've been encountering challenges trying to make the environment rotate around the character. Various attempts such as adjusting the camera position, grouping the camera with the model, or moving the model itself have led to the rotation occurring around the camera instead of the character (or anchor as indicated in the initial code). Any insights or suggestions on how I can achieve this properly using PointerLockControls would be greatly appreciated. Thank you!

Answer №1

If you happen to stumble upon this post in the future, I ran into a roadblock when searching for resources or examples on how to utilize ThreeJS' PointerLockControls to allow the user to orbit around the model instead of the camera after some changes were made to the API.

As a result, I decided to work with the basic PointerLock API, and surprisingly enough, it was relatively easy to achieve my desired outcome -

Here's a snippet of the code I used:

// Assuming canvas is defined
canvas.addEventListener('click', async () => {
    canvas.requestPointerLock()
})

document.addEventListener('pointerlockchange', handlePointerLock, false)

let isPointerLocked = false

function handlePointerLock (evt) {
    isPointerLocked = !isPointerLocked
    
    if(isPointerLocked) {
        // Get mouse events
        canvas.addEventListener('mousemove', mouseMoveHandler)
    } else {
        // remove event listening on pointer lock exit
        canvas.removeEventListener('mousemove', mouseMoveHandler)
    }
}

// Finally,
function mouseMoveHandler (e) {
    console.log(e.movementX)
    // I added my model as a parent to my camera
    // and rotated my model using the movementX data
    // Something along these lines -

    model.scene.rotation.y += e.movementX

}

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

Avoiding Rejected Promise: Warning for Error [ERR_HTTP_HEADERS_SENT] due to Issue with setInterval and Axios.post Error Management

I attempted to address this warning by researching online. Unfortunately, I couldn't find a solution, so I am reaching out with this question. The current warning that I am encountering is: (node:39452) UnhandledPromiseRejectionWarning: Error [ERR_H ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

What is the best way to remove an item from an array inside another object in JavaScript?

I am currently developing an application using Node, mongoose, and express. My goal is to remove an object from an array that is nested inside another object. Here is the structure of the objects: const oldSection = { _id: '62d3f1d221aa21a03fe3bc21& ...

Switch out the Select feature for Checkboxes

Hey there! I'm currently trying to enhance the style and functionality of the Select checkboxes on my blog. However, when I change them to checkboxes, they lose their original function of searching for selected tags in each Select option. This issue i ...

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

Error: The variable usersWithSecrets has not been declared and therefore is not defined within the current scope. This issue

Despite my best efforts, I keep encountering the same error repeatedly: ReferenceError: D:\Secrets - Starting Code\views\submit.ejs:8 6| <h1 class="display-3">Secrets</h1> 7| >> 8| <%usersWith ...

Tips for fixing the "Module not found" issue when executing a Node.js application

My Node.js application is encountering an issue when I try to run it using the npm start command. It appears to be failing to locate the entry point file, which results in a "Cannot find module" error. Here's the error message I'm seeing: > P ...

JavaScript encountered an Uncaught TypeError when trying to read the property 'length' of an undefined value within an array

Currently, I am encountering an issue with passing arguments into a function. When I pass two arguments into the specified array setup and try to log them using console.log, an exception is thrown. Strangely, if I remove the arguments from the parameters ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Examining the disparity between two dates through mocha/chai testing

I am currently utilizing "chai": "^4.2.0" and "mocha": "^6.1.4",. Upon using assert.equal() to compare two dates, I encounter a discrepancy where the comparison returns false despite the dates appearing the same. Here is an example of the situation: http ...

Marked checkboxes and Node.js

I'm having trouble grasping the concept of using HTML checkboxes with Node.js and Express. I have a basic form in EJS and before diving deeper into the backend logic, I want to ensure that the correct values are being retrieved. Despite my efforts to ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...

Having trouble finding the maximum and minimum dates with Moment()?

My task involves working with an array of dates and finding the maximum and minimum dates within it. Below is the code I've written for this purpose: let date_list = [ "2021-03-19T00:00:00Z", "2021-03-20T00:00:00Z", "2021-04-12T00:00:00Z", "202 ...

The font size appears significantly smaller than expected when using wkhtmltoimage to render

I am trying to convert text into an image, with a static layout and size while adjusting the font size based on the amount of text. I prefer using wkhtmltoimage 0.12.5 as it offers various CSS styling options. Currently, I am working on a Mac. Below is a ...

Proper retrieval of Promise outcomes

I am facing a challenge with loading textures in a class. I want the class to be called only after all textures have been loaded successfully. While I have managed to load the textures, I am unsure about where and how to call the class at the right time ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

Is it possible to showcase CSS and JavaScript code exactly as it appears when the files are saved in their respective formats, but embedded within an HTML

Recently, I've been working with notepad++ and have come across an interesting challenge. In my index.html file, I have embedded css and javascript code. Is there a way to display this code as it appears when saved in their respective files, but maint ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

Modify components in a web application based on the content of a JavaScript variable

I'm in the process of developing a webapp that needs to interact with an Arduino for its inputs in order to dynamically change the contents of the webpage. Currently, I am experimenting with variables that I have created and assigned random numbers t ...