Conceal items by clicking using raycasting technology

I'm trying to hide scene objects by clicking on them, but after following multiple tutorials on "raycaster", I'm having trouble identifying where the issue lies. When I open my HTML file, all the objects are hidden, even though I've removed most of the irrelevant code related to the raycaster.

    <script>

        if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

        var SCREEN_WIDTH = window.innerWidth;
        var SCREEN_HEIGHT = window.innerHeight;
        var FLOOR = -250;

        var container, stats;
         var  group1 , group2 , group3 ;
        var camera, scene, controls;
        var renderer;

        var mesh;
        var textureCube;
        var cameraCube, sceneCube;
        var loader;


        var mouseX = 0, mouseY = 0;

        var windowHalfX = window.innerWidth / 2;
        var windowHalfY = window.innerHeight / 2;

        init();
        animate();

        function init() {

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

            // CAMERA and controls

            ....

            // SCENE

            scene = new THREE.Scene();

            // SKYBOX

            .....


              //models

               group1=...
               group2=...
               group3=...


        cubes = new THREE.Object3D() ;
        cubes.add( group1 ) ;
        cubes.add( group2 ) ;
        cubes.add( group3 ) ;

         mouseVector = new THREE.Vector3();
        projector = new THREE.Projector();

            // LIGHTS
            lights...

            // RENDERER

            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
            renderer.domElement.style.position = "relative";

            renderer.autoClear = false;

            container.appendChild( renderer.domElement );

            //

            renderer.gammaInput = true;
            renderer.gammaOutput = true;

            // STATS

            stats = new Stats();
            container.appendChild( stats.domElement );

            // EVENTS

            window.addEventListener( 'resize', onWindowResize, false );
            window.addEventListener( 'mousemove', onDocumentMouseMove, false );


        }

        //

        function onWindowResize( event ) {

            ....
        }


        function onDocumentMouseMove(event) {
            mouseX = ( event.clientX - windowHalfX );
            mouseY = ( event.clientY - windowHalfY );
            mouseVector.x = 2 * (e.clientX / containerWidth) - 1;
            mouseVector.y = 1 - 2 * ( e.clientY / containerHeight );
        }


        //

        function animate() {

            requestAnimationFrame( animate );

            render();
            stats.update();

        }

        function render() {

            controls.update();

            cameraCube.rotation.copy( camera.rotation );

            renderer.clear();
            renderer.render( sceneCube, cameraCube );

        //raycast
             var raycaster = projector.pickingRay( mouseVector.clone(), camera );

            window.addEventListener( 'mousedown', onMouseDown, false );
            var onMouseDown = function ( event ) {
                     var intersects = raycaster.intersectObjects( cubes.children );
                      var intersection = intersects[0] , obj = intersection.object ;
                      obj.visible = false ; 
            };

            renderer.render( scene, camera );

        }

    </script>

Answer №1

Instead of performing a raycast on every frame during rendering, it is more efficient to use an Event Listener for raycasting on mouse clicks:

window.addEventListener( 'click', onMouseClick, false );
function onMouseClick( event ) {
    var hits = raycaster.intersectObjects( objects.children );
    var hit = hits[0], object = hit.object;
    object.visible = 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

What sets Vuex apart from a traditional store object?

I'm currently utilizing Vuex for Vue 2 which is similar to Redux for React. Recently, I came across a helpful example that demonstrates updating a counter. Here is the code snippet: import Vuex from 'vuex' import Vue from 'vue' V ...

Access information from multiple div elements using JavaScript data-attributes

Having trouble retrieving data-attribute values from multiple divs with the same class when clicked. The goal is to display the data value of the clicked div. function playSound(e) { const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`) ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Restrict dropping items in HTML5 by only allowing the drop if the target div is

I am working on developing a user-friendly visual interface for creating simple graphics. The interface includes 10 image icons and 5 boxes where users can place these icons. Users have the freedom to select which icon they want to display and arrange them ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

I must modify the initial statement to appear in bold from the paragraph with the use of JavaScript and CSS

Mr. XYZ and Mrs. ABC are known for their integrity. They own a stylish car. In the next paragraph, I would like to emphasize the first sentence by making it bold, We admire our exceptional leader J.K.L. He shows great potential. In this section, I wan ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

The use of async components in Vue.js with named imports

I understand how to dynamically load components asynchronously in Vue. For example, instead of importing MyComponent directly: import MyComponent from '@/components/MyComponent' export default { components: { MyComponent } } We can use ...

Update the text input field from a different webpage

I am working with two PHP pages, let's call them page1.php and page2.php. On page1.php, there is a textbox with a default value of 0, while on page2.php, there is a button. I have these two pages open in different tabs in a browser. My goal is to have ...

ExpressJs does not support query parameters with the router.get method

I am currently working on developing an Express app. Here is the code snippet I am using: const express = require("express"); const router = express.Router(); router.get("/:id", ControllerHandler(UserController.getSingle, GetUserReque ...

Utilize ExpressJS app.use to enable middleware functionality

As I delve into learning ExpressJS, my attention was drawn to a particular code snippet that has left me puzzled. The function app.use is perplexing me and the documentation isn't providing clear insight. Could someone shed some light on what exactly ...

5 Simple Steps for Adding a Value to a Popup Textbox Automatically

I want to send a value to another php page and then display the values. How can I achieve this? Here is the PHP code snippet: if(!empty($_POST["mytext"])) { for ($x=1; $x<=$a; $x++) { echo $txtLine[$x] = $_POST['mytext'.$x]; } } B ...

Importing pixi-sound in the right way for PIXI JS

I have a question regarding the proper way to import pixi-sound into my project. I am facing an issue with the following code snippet: import * as PIXI from "pixi.js"; import PIXI_SOUND from "pixi-sound"; const EFFECT_SOUNDS = [...list of music] for (le ...

Does it make sense to prioritize robust $routeProviders and keep controllers slim?

Traditionally in MVC architecture, models are designed to be robust and controllers are kept minimal for easier testing. However, Angular lacks a clear model structure, making it challenging to organize code for reuse. Although Angular does offer services ...

Unable to submit form upon clicking radio button in .NET Core

Trying to submit a form by clicking on a radio button. The JQuery code used for submitting the form: Form: @for (var item = 0; item < Model.Count(); item++) { <form id="myform" action="xx" controller="xxx" method="post"> ...

What is the technique for invoking methods of the Joi class without the need to instantiate an object?

I recently delved into using the Joi NPM module and found it confusing that although it is described as a class in the documentation, it does not require creating a class object like var joi = new Joi();. Can you explain how this works? My understanding o ...