The raycasting is running wild, responding without hesitation when it should only be triggered by a

I've encountered an issue with a script I created that is supposed to add a new plane to a scene every time I click on an existing plane using a raycaster for detection. However, the script is adding planes uncontrollably to the scene without any clicks happening. I'm not sure what I missed in the script. Can someone help me figure this out?

Thank you!

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;

var savedColor;

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 );
var material = new THREE.MeshBasicMaterial( {color: new THREE.Color( Math.random(), Math.random(), Math.random() ), side: THREE.DoubleSide} );
var plane = new THREE.Mesh( geometry, material );
plane.position.set( x, y, z );
scene.add(plane);

}
}

savedColor = null;

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

document.addEventListener( 'click', onDocumentClick, false );

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

container.appendChild( renderer.domElement );
scene.updateMatrixWorld();
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 );

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

var geometry = new THREE.PlaneGeometry( 60, 60 );
var material = new THREE.MeshBasicMaterial( {color: new THREE.Color( 0xffff00 ), side: THREE.DoubleSide} );
var plane = new THREE.Mesh( geometry, material );
plane.position.set( getRandomBetween(-300,300), getRandomBetween(-300,300), -20 );
scene.add(plane);
// console.log("hey!");

scene.updateMatrixWorld();

}
}

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

}

function getRandomBetween( min, max ) {
return Math.random() * (max - min) + min;
}

function onDocumentClick( event ) {

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

}

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

Answer №1

The reason for this issue is that the starting position of the mouse is set to (0, 0), causing it to intersect with the AxesHelper.

To fix this, you can either update the initial position of the mouse, remove the AxesHelper, or change the intersecting target to a specific group.

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

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

Tips on updating an object and adding it to an array in ReactJS with Material UI

Seeking guidance on editing an array of objects and displaying the updated value in the view. I'm new to ReactJS and attempted to do it as shown below, but found that after editing, I lose everything except for the specific one I edited. Can anyone co ...

Click on an element using jQuery to apply a specific class to all other similar

I am looking to dynamically add a class to a DIV after clicking on an A element with the same class. Here is an example: <ul> <li><a href="#1" class="test1">1</a></li> <li><a href="#2" class="test2">2</a>< ...

Is there a way to insert a label directly following a dropdown menu within the same table cell?

My goal is to include drop-down lists in a web page, so I decided to create a table structure using JavaScript. Firstly, I used the document.createElement() method to generate a table, table body, rows, and cells. Then, I proceeded to create select element ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

Loading images in advance with AJAX for enhanced AJAX performance

My website is structured in a sequential manner, where page1.html leads to page2.html and so on. I am looking to preload some images from the third page onto the second page. After searching, I came across this amazing code snippet: $.ajax({ url ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Unable to access Vue.js cookies: they are not defined

I integrated vue-cookies into my project successfully. In the main.js file, I added the following code: createApp(App) .use(store) .use(router, axios, VueCookies) The script section in App.vue file looks like this: <script> import Navbar fr ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

The inefficiency of invoking Jquery on elements that do not exist for the purpose of caching

What is the impact if JQuery attempts to access elements that do not exist? Will there be any significant CPU overhead other than script loading? Does it matter if this is done for a class or an id? For optimization purposes and to minimize simultaneous c ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Capture JavaScript results using PHP

I'm looking for a way to save the output or result of JavaScript code. For example: <script>document.write(navigator.appVersion)</script> When it comes to PHP, I have no issues: $ip = $_SERVER['REMOTE_ADDR']; $file = "log.txt ...

How to toggle two classes simultaneously using JQuery

Check out this code snippet: http://jsfiddle.net/celiostat/NCPv9/ Utilizing the 2 jQuery plugin allows for the following changes to be made: - The background color of the div can be set to gray. - The text color can be changed to red. The issue arises wh ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

'Unlawful invocation' problem occurs while attempting to upload a file using ajax

Having trouble with uploading a file using ajax as I keep running into an 'Illegal invocation' error when trying to pass the file. All other input fields are successfully passed (if I exclude the file). Here is a simplified version of my code: ...

Is there a way to trigger another API call when clicking a button in Vue.js?

I recently started using vue js and I am facing a challenge with this component. I am attempting to trigger another API call when one of the list options is clicked. <template> <div> <h1 class="text-center text-4xl font-bold">Our ...

Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling ...