Retrieve the vector3 that points in the direction of the pointerlockcontrols in Three.js

Exploring the feasibility of using the orientation of the yaw object in pointer lock controls as a direction for a raycaster. I've been experimenting with adding some basic shooter functionalities to the code. Despite trying various methods from stack overflow involving the X & Y values from the yaw object provided by the pointer controls, I haven't had any success yet. Here's my current attempt:

setupTarget: function() {
  //var vector = new THREE.Vector3(game.mouse.x, game.mouse.y, 0);
  var yaw = game.controls.getObject();
  var pitch = game.controls.pitchObject;
  var vector = new THREE.Vector3(
    yaw.position.x * Math.cos(pitch.rotation.x),
    yaw.position.y * Math.sin(yaw.rotation.y),
    0
  );
  var dir = vector.sub(yaw.position).normalize();
  this.ray = new THREE.Raycaster(yaw.position.clone(), dir);
}

I'm aware that it's incorrect and not functioning properly. I mistakenly mixed up some calculations for translating x & y based on rotation, which obviously doesn't apply to the target.

Answer №1

To implement the following feature in your version of PointerLockControls, follow these steps:

this.calculateDirection = function() {

    // Assuming no rotation on the camera

    var direction = new THREE.Vector3( 0, 0, -1 );
    var rotation = new THREE.Euler( 0, 0, 0, "YXZ" );

    return function( v ) {

        rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );

        v.copy( direction ).applyEuler( rotation );

        return v;

    }

}();

Make sure you are using three.js r.59

Answer №2

Unfortunately, the latest update is causing some issues. To make it work, I now have to include:

var vector = new THREE.Vector3( 0, 0, -1 );

prior to:

vector.copy( direction ).applyEuler( rotation );

This additional step is necessary due to Firefox not being able to recognize the variable 'vector'.

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

What is the reason behind the cross-origin error thrown by JSON.parse?

When I don't use JSON.parse, my code works perfectly fine. However, as soon as I attempt to parse or stringify my data object, a cross-origin error is thrown. Why is this occurring and what steps can I take to resolve it? The snippet of code in Title ...

We encountered an issue: Headers cannot be set after they have been sent while attempting to read files

I encountered an error when attempting to read a file and send the response back to the browser. [ 'Error: Can\'t set headers after they are sent.', ' at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)&apo ...

Is it possible to verify the presence of data in a database using the ajax method?

This piece of JavaScript code is responsible for validating mobile number data, among other information, and sending it to validate_user.php for storage. However, I only want to store the data of users whose mobile numbers exist in another table; otherwise ...

What is the best way to send several arguments to the onSuccess function in Prototype?

I am new to utilizing the Prototype library and I was wondering how it is possible to pass multiple arguments to the onSuccess/onFailure functions in Prototype. Let's say, for example: new Ajax.Request('testurl',{ method: 'post ...

What causes the for loop to run indefinitely?

window.TicTacToet.compMove = function (row, col) { var player = window.TicTacToet.PlayerTurn; var board = window.TicTacToet.Board; for (i = 0; i < window.TicTacToet.Board.length; i++) { for (j = 0; j < window.TicTacToet.Board[ ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...

Functionality not working when clicked on iPhones

I'm facing an issue with my dropdown menu that appears when an image is clicked. Below is the relevant HTML code snippet: <div class="menu"> <img id="menu_img" src="https://res.cloudinary.com/dqn5eqmwt/image/upload/v1493014197/Menu ...

Switching background images for DIVs when links are rolled over

Having trouble changing the background image of a div when a user hovers over a link. Any ideas on what might be causing this issue? <style> #divToSwap { background-image: url(black.jpg); height: 150px; width: 150px; } </style> &l ...

Express JS with multer is unable to process multiple file uploads, resulting in an empty array being

As I develop an app on Glitch with express js, the functionality requires users to upload multiple files. Here is the code snippet that I am using: var express = require('express'); var cors= require('cors'); var bodyParser= requir ...

Error possible in modal due to interaction between JavaScript, PHP, and Bootstrap - Unable for PHP file to successfully retrieve value from JavaScript file

I have an existing database that is already populated. Additionally, I have a JavaScript function that captures the ID of the element when a button is pressed. Here's an example: Name of Subject | Actions -------------------------------------- ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...

Is there a way to adjust the padding temporarily?

Important Note: Despite the misleading title of my question, it doesn't accurately reflect my actual query (sort of). Below is the code snippet in question: .one{ background-color: gray; } .two{ padding: 20px; } <div class = "one"> < ...

Ways to turn off hover highlighting

Is there a way to disable the highlighting effect of the <select> element in HTML? When you hover over items in the dropdown list, a blue color strip moves with your mouse. I need to find a way to get rid of this effect. Here is an example of the c ...

Handling Errors with Symfony 5 JSON Responses and VueJS Using Axios for Customized Error Messages

I need to show a personalized error message when my JSON response throws an error. Some of my services trigger an error like this: if (count($recipients) === 0) { throw new TransportException($this->carrierService::ERROR_NO_MAIL_ADDRESSES); } The ...

Enable Intellisense for my custom ES6 JavaScript modules in VS Code

Using VS Code Intellisense can greatly enhance productivity when working with internal project files, providing helpful autocompletion features and utilizing written JSDoc comments. However, my current projects involve custom JavaScript libraries stored i ...

Issues with Pageinit and Ready Event Timings

Check out this fiddle where I am experiencing an issue related to pageinit and ready events In the fiddle, everything functions properly using onLoad and onDOMready. This includes: The subject listings are loaded correctly with a popup displaying module ...

spinning div content in a manner reminiscent of a roulette wheel

I am looking to create a roulette game that randomly selects numbers and displays them. Initially, I attempted to use images and backgroundOffset, but it caused significant lagging issues and difficulty in checking the rolled number. Therefore, I have impl ...

What is the reason for this JavaScript code not activating the input field (aspx)?

Thank you for taking the time to review this. I understand that for most of you client side scripting experts, this task is a breeze. However, all I am trying to achieve is to display a message at the top notifying the user that their click has been regist ...

Using bootstrap can alter the positioning of elements that have margins relative to other elements

After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable attribute can achieve dragging, its limitations and side effects are something I aim to avoid. ...

Confirm the Text Box with JavaScript

I'm struggling with validating the textbox on my login Xhtml. Once I finally cracked the code, I encountered an issue with the 'container' class in the section. How can I properly write the code and successfully validate the textbox? <h ...