The Three.js raycaster is already picking up on objects before I even start moving the mouse

I'm experimenting with the Three.js raycaster and have created a grid of planes that are supposed to start off yellow and turn red when you hover over them with the mouse. However, the issue I'm facing is that when I run the script, all the planes turn red even before I move the mouse. Can someone help me figure out what I've done wrong? Thanks!

var container, renderer, scene, camera;
var container = document.body;

var frustumSize = 1000;

var width, height;

var numRows = 4;
var numCols = 7;
var spacingSize = 300;

var raycaster;
var mouse;

function init() {

    width = window.innerWidth;
    height = window.innerHeight;

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor(0x000000);

    scene = new THREE.Scene();

    var aspect = window.innerWidth / window.innerHeight;
    camera = new THREE.OrthographicCamera( frustumSize * aspect / - 2, frustumSize * aspect / 2, frustumSize / 2, frustumSize / - 2, 0, 2000 );
    // camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 0, 2000 );
    camera.updateProjectionMatrix();


    // set up grid of colored planes

    var startXPos = -((spacingSize*(numCols-1))/2);
    var startYPos = -((spacingSize*(numRows-1))/2;

    for ( var i = 0; i < numCols; i++ ) {
        var x = startXPos + (i*spacingSize);

        for ( var j = 0; j < numRows; j++ ) {
            var y = startYPos + (j*spacingSize);
            var z = -10 + (j * -1.0001);

            var geometry = new THREE.PlaneGeometry( 50, 50, 32 );
            var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
            var plane = new THREE.Mesh( geometry, material );
            plane.position.set( x, y, z );
            scene.add(plane);

        }
    }

    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();

    window.addEventListener( 'mousemove', onMouseMove, false );

    // click to select and save the values of one and high light it

    // click to select another

    // combine the color values of the two and produce several "children" in the display

    var axesHelper = new THREE.AxesHelper( 100 );
    scene.add( axesHelper );

    container.appendChild( renderer.domElement );
    render();
    
}

function render() {

    // update the picking ray with the camera and mouse position
    raycaster.setFromCamera( mouse, camera );

    // calculate objects intersecting the picking ray
    var intersects = raycaster.intersectObjects( scene.children, true );

    // calculate objects intersecting the picking ray
    if ( intersects.length > 0 ) {
        //console.log("yo!");
        for ( var i = 0; i < intersects.length; i++ ) {

            intersects[ i ].object.material.color.set( 0xff0000 );

        }
    }

    renderer.render( scene, camera );
    requestAnimationFrame( render );
}

function onMouseMove( event ) {

    event.preventDefault();
    // calculate mouse position in normalized device coordinates
    // (-1 to +1) for both components
    //console.log("hey!");
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

}



// window.requestAnimationFrame(render);

init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/106/three.js"></script>

Answer №1

Before rendering for the first time, make sure to manually update the world transforms if you are using raycaster.intersectObjects().

scene.updateMatrixWorld();

Include this line in your init() function.

For three.js version r.106

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

Ways to retrieve HTML content from various spans and incorporate the values as classes

Here is my custom HTML: <div class="box"> <ul class="fourcol first"> <li class="feature-item">Description: <span>0</span></li> <li class="feature-item">Description: <span>0</span></ ...

What is the process for javascript selecting a remote-data service?

I recently purchased a new app and am diving into Javascript and AngularJS for the first time. As I try to navigate through the code, I find myself puzzled by how the function in homeService.js is able to utilize remote-data.service.js. Featured below is ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Nuxt issue: Vue router push not reflecting query updates

Recently, I encountered an issue with vue-router-query. When using a click event to navigate to the filter page and append the URL query to it, there seems to be a problem with updating the query data dynamically. The function responsible for sending the q ...

What is the best way to locate a specific item within an array of objects, especially when each object has the potential to contain an array of objects of the

I am grappling with the challenge of finding a specific object within an array of objects, where the desired object may be nested within another array of one of the objects. I have experimented with various iterations of forEach loops and recursion method ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

Mastering VSCode IntelliSense: Unleashing the Power of Type Declarations

In my JavaScript projects, I aim to include TypeScript types sparingly to leverage IntelliSense for better code completions and receive warnings about type-related issues. To set up typechecking in JS, I created a jsconfig.json file and rely mostly on JSD ...

How can I efficiently create an editForm in Angular?

Within my database, there are numerous users, each with their own collection of recipes. Each recipe contains various properties and a list of ingredients. Take a look at the screenshot below: Recipe with all properties When a user goes to edit a recipe ...

Middle-Click JavaScript Action

On the website I'm currently working on, there is a button that uses a sprite sheet animation and therefore needs to be set as a background image. I want the button to have a slight delay when clicked, so the animation can play before redirecting to a ...

Why is the UI Router controller failing to function properly after loading the view from the $templateCache?

I've been utilizing gulp-angular-templatecache to convert my filename.view.html files into a consolidated templates.js file. Afterwards, I use $stateProvider to define states and fetch the templates from $templateCache, including an abstract "root" s ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

Manipulating the value of an array obtained from an API alters its data when trying to log it in the render function of a React TSX component

My program can fetch data from an API I created using a component that interacts with the backend: import React, { Fragment, useEffect, useState } from 'react' import { Button, Stack } from '@mui/material'; import TabsComponent from &ap ...

Error Alert: The combination of React and Redux-router is causing an unexpected issue. The reducer is expected to be a

Whenever I make a coding mistake and encounter a runtime error, the error reporting is not very helpful. For example, when I mistakenly typed Date() instead of new Date(), the error message I received was... Uncaught Error: Expected the reducer to be a fu ...

Utilizing live function for event handling in jQuery

Hello there, I have encountered an issue while using jQuery 1.3, specifically with the live event where the element "context" is bound to the default document root. Can you suggest a way to address this problem? According to the jQuery documentation: ...

FullCalendar jQuery caught in an endless loop

After successfully implementing drag and drop deletion, I encountered a new issue. Whenever I delete an event, the removal process functions properly but then the code gets stuck in a loop within the eventDragStop function causing the calendar to freeze ...

Verifying conditions within an array of objects in JavaScript

Verify an array of objects based on certain conditions. The array of objects starts off empty. 1. If the array is empty and an action occurs, add an object to the array. 2. If the array already contains an object, check if it already exists. If it does, ...

Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried: button.style.className = '' document.querySelector('button').onclick = function() { this.style.className = ''; } .myClas ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...