The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to the camera itself. Here's a snippet of the code:

function cameraController(cam, scene){
    // Implementation details here...
}

Despite successfully implementing the camera controller, I encountered an issue where raycasting fails to detect meshes when the camera and its parent object are being moved simultaneously.

Here's the relevant raycasting function:

document.addEventListener('click', function(event) {
    // Raycasting logic here...
}, false);

I've attempted using methods like "cam.updateMatrix()" and "cam.updateProjectionMatrix", but unfortunately, they didn't resolve the issue. Even after making the camera a child of the Object3D, the initial positions remain unchanged (0, 10, -4). If anyone has insights on why raycasting isn't functioning properly when using this controller to move the camera, I'd greatly appreciate your input.

Answer №1

For anyone struggling with a similar issue, I wanted to share a solution that may not be perfect, but it gets the job done. At the start of the click event, I saved the world and camera positions. Then I detached the camera from its parent, positioned it in the world coordinates, and added it back to the scene. After raycasting, I removed the camera from the scene, reset its position to the previously saved local coordinates, and then reattached it to the base object.

document.addEventListener('click',function(event){
    var px = camera.getWorldPosition().x;
    var py = camera.getWorldPosition().y;
    var pz = camera.getWorldPosition().z;
    var pxx = camera.position.x;
    var pyy = camera.position.y;
    var pzz = camera.position.z;
    camcont.baseobject.remove(camera);
    camera.position.set(px,py,pz);
    scene.add(camera);
    event.preventDefault();
    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects(scene.children);
    if (intersects.length > 0) {
        console.log("intersects !!");

    }
    scene.remove(camera);
    camera.position.set(pxx,pyy,pzz);
    camcont.baseobject.add(camera);
},false);

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

How come my variable doesn't show up in the view even though I filled it in the controller?

I'm having trouble with my AngularJS setup. The angular.min.js file is located in the js folder, following a code example from O'Reilly's book. However, for some reason it is not working on my computer. //controller.js function HelloCont ...

Executing Javascript without invoking the default behavior

Recently, I've been delving into the world of JavaScript and experimenting with the prevent default command for ajax pagination. Here's the code I've come up with: http://jsfiddle.net/6pqfH/2/ $('.pagination').click(function(e){ ...

Retrieve both the key and corresponding value from a JSON object

I am attempting to extract the key and value pairs from a JSON dataset. $.get(url, function (data) { console.log(data); if (data.Body != null) { console.log(data.Body); } }); These are my current logs: { $id: "1", Exceptions ...

Transitioning from a see-through navigation bar to a vibrant colored menu as

I consider myself a novice when it comes to JavaScript. My goal is to create a Transparent Menu that smoothly transitions from transparent to white with a box shadow as I scroll down the page. However, the JavaScript code I have implemented does not seem ...

Retrieve and update the most recent entry

Here is the schema I am working with: var BudgetInfoSchema = mongoose.Schema({ user_email: { type: String, required: true }, user_budget: { type: Number, required: true }, platforms_budget: { type: [{ platform_id: { type: String, required ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

Transfer data from a file to a PHP file using the XMLHttpRequest object in JavaScript and receive

I'm attempting to use AJAX to send an image file to a PHP file. The issue is that even though the script sends the object, my parser isn't able to retrieve the $_FILES["avatar"]["name"] and tmp_name values. Is there a method to transfer the file ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...

Creating a new dynamic page can be achieved by clicking on a dynamically generated link. Would you like to learn how to do that?

Recently, I developed a custom API using Node.js to retrieve information about blogs from Medium.com. The API currently provides: The author/main picture of the article Title A link to the article on medium.com (redundant) The entire article text in the ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...

Responsive Fullscreen Bootstrap Panel with Highcharts

One issue I'm facing is with my (bootstrap) panels that contain Highcharts charts and I want them to show fullscreen without losing their aspect ratio. The problem is that the size of the Highcharts does not adjust when going into full-screen mode. Is ...

Error: The component passed is invalid and cannot be defined within kendo UI

Check out this example https://www.telerik.com/kendo-vue-ui/components/grid/ showcasing a computed method gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all colu ...

While creating a React app, Docker becomes stuck due to a hangup when checking the core-js dependency

I've hit a roadblock in the build process. I'm working on an M1 Mac Mini and have attempted to build in both arm64 and x86_64 terminals, but the outcome is consistently the same. npm info lifecycle @babel/<a href="/cdn-cgi/l/email-protection" ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

The act of appending values to an array within a hash in Vue is not functioning as expected

I am currently working on implementing a feature that allows users to add multiple workers by clicking the "Add worker" button. However, I have encountered an issue where placing the workers array inside the management object prevents this feature from f ...

My code in NodeJS is not executing in the expected order due to its asynchronous nature

handleRegistration: function (user, req, res, next) { console.log('handleRegistration activated'); user.getData(function(err, info) { if (err) { console.log(err.toString, "error message"); return next(err); } e ...

Connect individuals based on specific criteria within a nested array

My MongoDB collection looks something like this: _id: ObjectId("5cb089e459552d8b8cc6a9e4") username: "admin" password: "12345" gender: "male" interestedIn: "female" movie: Array 0: Object id: "Avatar" title: "Avatar" poster: "~" 1: Object ...

"Enhance Your Website with qTip2 Feature to Load Multiple AJAX Sites Simult

I'm currently utilizing the qTip2 library for my project and I've implemented their AJAX retrieval functions following this example: http://jsfiddle.net/L6yq3/1861/. To enhance my query, I have modified their HTML to include multiple links. The ...