Updating an object's matrix in THREE.js after adjusting its position using Raycaster

I'm encountering an issue with FPS camera controls in a three.js scene. My approach involves using a Raycaster to determine the camera group's position by intersecting it with the scene along the Y axis (a makeshift gravity setup) and then applying user input for movement. However, the camera group's position keeps resetting to the intersection location on every frame, essentially sticking you in place.

I suspect this problem may be due to either an updateMatrix() issue or passing a Vector3 by reference somewhere, but I'm struggling to pinpoint the exact cause. Can someone please assist me? Here is the code snippet for better understanding:

re-renderer.setAnimationLoop((event) => {

    if (clock.running) {

        update();

        renderer.render(scene, character.view);

    }

});

clock.start();


// 


const update = () => {


   // velocity


   const speed = new THREE.Vector3();

   speed.x = input.controller.direction.x;
   speed.z = input.controller.direction.y;

   speed.clampLength(0, 1);

   if (speed.z < 0) {

      speed.z *= 1.4;

   }


   // gravity


   if (scene.gravity.length() > 0) {

      const origin = new THREE.Vector3().copy(character.view.position);
      const dir = new THREE.Vector3().copy(scene.gravity).normalize();

      const interact = new THREE.Raycaster(origin, dir).intersectObjects(scene.collision).shift();

      if (interact) {

         character.group.position.copy(intersect.point);

         character.group.updateMatrix();

      }

   }
...

The camera configuration is similar to the PointerLockControls helper, with the camera as a child of a Group Object for yaw and pitch. The controller input, sourced from either a mouse or gamepad, returns normalized values.

The main culprit seems to be here:

   // gravity


   if (scene.gravity.length() > 0) {

      const origin = new THREE.Vector3().copy(character.view.position);
      const direction = new THREE.Vector3().copy(scene.gravity).normalize();

      const inter = new THREE.Raycaster(origin, direction).intersectObjects(scene.collision).shift();

      if (inter) {

         character.group.position.copy(intersection.point);

         character.group.updateMatrix();

      }

   }

By commenting out

character.group.position.copy(intersection.point);
, the camera moves correctly (albeit floating), but otherwise it moves a single frame's distance before reverting back to the intersection point on the next frame.

I've experimented with various methods like updateMatrix(), updateMatrixWorld(), updateProjectionMatrix(), and setting Object.matrixWorldNeedsUpdate to true, yet haven't found a solution.

Apologies for not providing a testable scenario and instead relying on code snippets. I appreciate your time and assistance.

Answer №1

Wow, sometimes the simplest mistakes can trip us up... Using

const origin = new THREE.Vector3().copy(character.view.position);
gave me local space coordinates instead of what I needed.

But when I switched it to

const origin = new THREE.Vector3().setFromMatrixPosition(character.view.matrixWorld);
, everything worked perfectly.

It just goes to show, staring at your code for too long can lead to overlooking the obvious. Hopefully this experience will benefit someone else down the line.

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

Incorporate dc.js into your Cumulocity web application

Our team is facing a challenge while trying to integrate dc.js into our Cumulocity web application. While the standalone version works perfectly, we encounter issues when attempting to use it within Cumulocity. Below is the code for our standalone applica ...

Real-time file uploading feature

I'm currently working on a jQuery live file upload feature. Within my application, there's a form that includes a file field. When a user selects a file, I want to initiate an AJAX file upload method. However, the actual file upload will occur l ...

JavaScript: transform all repetitive elements in the array

One interesting example in my code. var array=[[1,'a'],[1,'b'],[2,'c'],[2,'b'],[2,'d'],[3,'a'],[3,'s'],[3,'w'],[3,'q'],[4,'w']] Desired output is as below ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Error: JSON parsing failed due to an unexpected character 'W' at the beginning

I am encountering an issue while sending a POST Request through the API in JavaScript. The method I have been using for multiple POST Requests is now displaying the error message: SyntaxError: Unexpected token W in JSON at position 0 Below is the snippet ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with: "ACCOUNT": { "AmountDue": "$36,812.99", "OutstandingBalance": "$27,142.27", "StatementTotal": "$9,670.72", "StatementDate": "12/6/2018", "DueByDate": "12/23/2018", ...

"The issue I'm facing with Next.js is that the fetched data is not displaying in the template. Additionally, I'm

I am encountering an issue with my API data where it is being called twice in the terminal. Additionally, I am trying to display this data on my page template but for some reason, it is not showing up. Here is the code snippet in question: Here is my code ...

Is there a way in Vue to efficiently route multiple instances belonging to the same component while ensuring they maintain their individual states?

It's a bit difficult to capture the exact issue in the title. Here is the scenario: // In the main layout page <keep-alive> <router-view /> </keep-alive> // And I have a route { path: "something/:id", name: "someth ...

How can I use Chart.js to assign a unique color to each x-axis label?

I'm currently using Chart Js to create a chart and I want each label to have a different color instead of all labels having the same color. Is there a way to achieve this using the ticks callback function? scales: { xAxes: [{ ...

Generating exportable dynamic code in Javascript

Any assistance or links to similar inquiries would be greatly welcomed as I have conducted some research but am uncertain about the best approach to take in this situation. I find it difficult to articulate exactly what I need, so I have created a visual ...

Arranging a map by its keys results in a sorted Map object with the initial key located at the end of

I have a function that creates a Map object from two arrays and then attempts to sort the map by key. Despite following the sort method as outlined in Mozilla Docs, the sorting is not working as expected; it places the first key at the last index when usin ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Have you ever come across odd ways to use Array.of() and Array.from()?

Discover two innovative methods introduced in ES6 for Array: Array.of() and Array.from(). Their distinct uses are outlined on this informative page. However, I find myself perplexed by the application of Array.of in this specific line. // usage of Array. ...

Disabling past dates in a React JS application with a React date picker

Can someone help me figure out how to prevent selecting past times in React JS? Here is the code snippet: import DatePicker from "react-datepicker"; import setHours from "date-fns/setHours"; import setMinutes from "date-fns/setMi ...

Tips on revitalizing a bootstrap wizard

In my JSP file, I am using a Bootstrap wizard. You can see the wizard layout in the following link: The wizard allows me to add employee elements that are stored in a JavaScript array (I also use AngularJS). At the final step of the wizard, there is a su ...

Navigating back to the previous page while retaining modifications using AngularJS

When I use the products table to conduct an advanced search, view details of a specific item and then click on the cancel button to return to the list, all my research inputs are reset... Is there a way for me to go back to where I was before? Can I retri ...

iOS users may find that when a web page loads, it is often already scrolled halfway down

Encountering a problem with a long-scroll website that I'm currently developing. Whenever I access the page on my iPhone, the initial scroll position is consistently halfway down or near the bottom of the page. I've attempted to troubleshoot by d ...

Incorporate an Ajax request onto an existing link within a div element

Here is what I have: <div id="div-for-ajax-onclick"> <a href="http://www.google.com">Link to google</a> </div> $("#div-for-ajax-onclick").click(function() { // update database }); I am looking for a solution where if someone c ...