The raycaster doesn't remain centered when I'm updating the camera position

Hey there, I'm facing an issue with Raycasting and haven't been able to solve it yet. I need some help with keeping the Raycaster in the center at all times. Even when I move my camera and look in different directions, I want the Raycaster to remain in the center and update accordingly. Here's the code snippet I'm using with raycasting:

var raycaster = new THREE.Raycaster();
var arrow = new THREE.ArrowHelper( raycaster.ray.direction, raycaster.ray.origin, 100, Math.random() * 0xffffff );
scene.add( arrow );
var intersects;
function sec(){
 requestAnimationFrame(sec);
    var directionVector = new THREE.Vector3();
        var positionVector = new THREE.Vector3();
    var b = camera.getWorldDirection(directionVector);
    var c = camera.getWorldPosition(positionVector);

    raycaster.setFromCamera( b,camera );
                
    arrow.position.copy(camera.position);
    arrow.setDirection(raycaster.ray.direction);

    intersects = raycaster.intersectObjects( scene.children );
    if(intersects.length>0){
        intersects[0].object.material.color.set( 0xff0000 );
      }
        else if(intersects.length<1 && casted){
        for(var i=0; i<arr.length; i++){
             arr[i].material.color.set( 0x8f8f8f );
        }
    }
    camera.updateProjectionMatrix();
    camera.updateMatrixWorld(); 
}

Would appreciate any guidance on this, thanks!

Answer №1

For a solution, refer to the Raycaster.setFromCamera() documentation. It states that the first parameter should be a Vector2 containing mouse coordinates within the [-1, 1] range. To target the center of the screen, set both X and Y values to 0:

// Placing mousePosition at (0, 0) centers it on the screen 
var mousePos = new THREE.Vector2(0, 0);
raycaster.setFromCamera(mousePos, camera);

intersects = raycaster.intersectObjects(scene.children);
if(intersects.length > 0){
    console.log(intersects[0]);
}

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

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

Validation of forms using ajax and javascript

I have implemented ajax on my webpage to dynamically change the content of a main div when different fields in the navigation bar are clicked. However, I am encountering a problem with form validation using JavaScript on elements loaded via ajax. For insta ...

Invoking the .html(result) function multiple times within the AJAX success callback

I have implemented this code in my template to handle my ajax request: <script> $(document).ready(function() { $("#send-mail-button").click(function(e){ e.preventDefault(); var nameVar = $('#name&apo ...

Is there a way to confirm if one field value is greater than another using the Ajv JSON schema validator?

Is it feasible to receive a validation error using ajv when minPrice exceeds maxPrice? What is the recommended method of achieving this, ideally adhering to the JSON schema standard? ...

Error in HTML: Text variable is not displaying the number value

Currently, I am facing a challenge with my code. I have a variable named "Timer" that I want to increment by one and then display the number. However, I am unable to see the "Test Successful!" message displayed on the screen. Surprisingly, there are no e ...

Access JSON file without considering any custom comments

Is there a way to extract the JSON data from 'file.json' without including any comments? # Comment01 # Comment02 { "name": "MyName" } I have tried using this code snippet: var fs = require('fs'); var obj; fs.readFile('./file. ...

What is the best way to store a personalized configuration for a user within a Node module?

For my CLI project in Node.js utilizing commander.js, I am interested in implementing a way to store user-specific configuration settings. This will allow users to input their preferences only once during the initial usage. What would be the best approac ...

Building a 3D Earth model using three.js for WebGL applications

I found a code online, but it doesn't seem to work. Can someone provide me with the HTML code needed to make it run in my browser? The original code was sourced from this website (github repository) Github code repository https://github.com/turban/ ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: https://i.sstatic.net/iBSof.png I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

What could be the reason for my reset function not halting?

Why does my reset button keep clearing the canvas and emptying the chat box even though the return statement is supposed to end the function? Main.js var reset = function() { context.clearRect(0,0, canvas[0].width, canvas[0].height); context.be ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

The setState function in ReactJS seems to be failing to properly update the fields

I am having trouble resetting the value of my input type to empty after storing data from a controlled form element. The first method below is not working for me, even though I'm using setState to clear the input fields. Can someone help me understand ...

Changing the filepath for the build script in the package.json file for a NextJS project when deploying to Heroku

My project is currently structured as Root: Folder 1/ Folder 2/ Folder 3/ .. Frontend/ The front end folder contains my Nextjs project, package.json file, and everything else. However, Heroku requires the content in the Frontend/ folder to be in the root ...

What is the best way to implement JQuery in order to trigger an event in a text box whenever the user hits the "enter

Also, refrain from submitting the form if the user hits enter in THAT PARTICULAR input field. ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

Using an Ajax call to show a date picker when a button is clicked

I've created buttons for each ID in the "habitaciones" table. When a button is clicked, it should display a specific datepicker with dates disabled for that ID. To achieve this, I utilized an Ajax function where the form should be displayed based on ...

I encountered a problem when making multiple JSON calls within a for loop

for(var j = 0; j < tempArray.length; j ++){ $.getJSON('http://localhost:8080/predict', tempArray[j]) .fail(function(data,textStatus, error) { Probability = data.responseText; console.error("getJSON failed, status: " + textStat ...