Identify circular surfaces in three.js

I've successfully developed a dynamic scene using three.js, featuring a textured and meshed cylinder along with a grid containing lines and vertices. The cylinder is programmed to have a spinning effect when the mouse is dragged left or right.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>3D Modeling with HTML5 and three.js</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: #f0f0f0;
                margin: 0px;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

        <script src="three.min.js" type="text/javascript"></script>
        <script src="Stats.js" type="text/javascript"></script>
        <script src="Detector.js" type="text/javascript"></script>

        <script>
            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var container, stats;

            var camera, scene, renderer, light, projector;
            var particleMaterial;
            var cylinder, line, geometry, geometry1;

            var targetRotation = 0;
            var targetRotationOnMouseDown = 0;

            var mouseX = 0;
            var mouseXOnMouseDown = 0;

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

            var objects = [];

            var radius = 1600, theta = 45, onMouseDownTheta = 45, phi = 60, onMouseDownPhi = 60, isShiftDown = false;
            init();                     
            animate();

            function init() {

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

                var info = document.createElement( 'div' );
                info.style.position = 'absolute';
                info.style.top = '10px';
                info.style.width = '100%';
                info.style.textAlign = 'center';
                info.innerHTML = 'Drag to spin the cylinder<br/>Objective: By spinning left, the cylinder should go into the surface and by spinning right it should come out.';
                container.appendChild( info );

                // camera

                camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
                camera.position.y = 200;                
                camera.position.z = 800;


                // scene

                scene = new THREE.Scene();

                // light

                scene.add( new THREE.AmbientLight( 0x404040 ) );
                light = new THREE.DirectionalLight( 0xffffff );
                light.position.set( 0, 1, 0 );
                scene.add( light );

                // texture              

                var materials = [];

                for ( var i = 0; i < 6; i ++ ) {

                    materials.push( new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) );

                }//alert(materials.length);

                // Grid

                geometry = new THREE.Geometry();
                geometry.vertices.push( new THREE.Vector3( - 500, 0, 0 ) );
                geometry.vertices.push( new THREE.Vector3( 500, 0, 0 ) );

                for ( var i = 0; i <= 20; i ++ ) {

                    line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
                    line.position.z = ( i * 50 ) - 500;
                    scene.add( line );

                    line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
                    line.position.x = ( i * 50 ) - 500;
                    line.rotation.y = 90 * Math.PI / 180;
                    scene.add( line );
                }


                // cylinder                                         
                geometry1 = new THREE.CylinderGeometry(100, 100, 300, 16, 4, false);

                cylinder = new THREE.Mesh(geometry1 ,new THREE.MeshLambertMaterial( { color: 0x2D303D, wireframe: true, shading: THREE.FlatShading } ));
                //cylinder.position.x = 100;
                cylinder.position.y = -50;
                //cylinder.overdraw = true;
                scene.add(cylinder);
                alert(geometry1.faces.length);
                objects.push(cylinder);


                // projector
                projector = new THREE.Projector();

                // renderer

                renderer = new THREE.CanvasRenderer();
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );               

                // stats

                stats = new Stats();
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.top = '0px';
                container.appendChild( stats.domElement );

                document.addEventListener( 'mousedown', onDocumentMouseDown, false );
                document.addEventListener( 'touchstart', onDocumentTouchStart, false );
                document.addEventListener( 'touchmove', onDocumentTouchMove, false );               

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

            }

            function onWindowResize() {

                camera.left = window.innerWidth / - 2;
                  // Remaining codeblock copied as is since its source code.

            function onDocumentMouseDown( event ) {         

                // Remaining codeblock copied as is since its source code.

            }

            function onDocumentMouseMove( event ) {

                // Remaining codeblock copied as is since its source code.

            }

            // Additional functions remain unchanged from the original text...

        </script>

    </body>
</html>

Is there a method to determine which face of the cylinder is being selected upon clicking?

Answer №1

To interact with the cube in the virtual environment, you need to shoot a ray from your viewpoint towards the cube. By doing so, you can determine the face or faceIndex of the object where the ray intersects.

function onDocumentMouseDown( event ) {

            event.preventDefault();

            // Calculate mouse position relative to screen
            var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
            projector.unprojectVector( vector, camera );

            // Create a ray from the camera through the vector
            var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );

            // Array of objects intersected by the ray (ordered front to back)
            var intersects = ray.intersectObjects( objects );

            // Check if we hit something
            if ( intersects.length > 0 ) {

                // Log the first intersection object (Mesh,...)
                console.log(intersects[0].object);

                // Get the face as a THREE.Face3/4 object
                console.log(intersects[0].face);

                // Get the face index as an integer
                console.log(intersects[0].faceIndex);

                // Change color of the intersected object for fun
                intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );

        }
}

Don't forget to explore the canvas_interactive_cubes example as well!

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

I'm experiencing a delay when trying to update data in MongoDB using Node.js

Here's the code snippet I'm working with: Datas.findOneAndUpdate({"_id":req.body._id}, Update(req.body)) .then((data)=>{ res.json({data}) }) After updating my database, the changes aren&apos ...

The container is not showing the JSTree as expected

My current project in JavaScript involves integrating a JSTree structure, but I'm encountering an issue where the tree is not showing up or rendering within its specified parent container. Below is the snippet of code I have been using to attempt to d ...

When trying to execute cordova, meteor.js encounters an issue locating the is-property module

Error image After encountering the error above, I decided to try accessing the program on a different computer - and surprisingly, it worked flawlessly. On my main machine, I have meteor, npm, is-property, and node all installed and functioning correctly. ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Using a script to properly close HTML tags

It seems like a straightforward task, but I'm not sure where to start looking for the solution. What I'm trying to accomplish is this. I have a script that scans for the strings [gallery]. When it finds [gallery], it replaces the tag with an ima ...

How to Trigger a Javascript Function from a Wordpress Navigation Menu

On my website developed in HTML, I have the ability to invoke any JavaScript function using an anchor tag like this <a href="javascript:function();"></a> However, when attempting to add this to a WordPress menu option and saving the menu, eve ...

Omit specific object properties within a foreach loop in jQuery AJAX

Check Out This Fiddle Example I am currently working with a PHP file that returns JSON data for main content along with an additional property for pagination. I am looking for a way to exclude the pagination property when iterating over the data in a fore ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

Utilize HTML5 and Javascript to easily upload files from your desktop through the drag and drop feature

I have created a drag and drop functionality for uploading images from the desktop to the browser. When I drop the image inside the designated box, I can view the image details in the browser console: File { name: "deam230mthumb.jpg", lastModified: 119464 ...

Updating the query parameters/URL in Node.js's request module

In my Express.js application, I am utilizing the npm request module to interact with an internal API. The options passed to the request function are as follows: requestOptions = { url : http://whatever.com/locations/ method : "GET", json : {}, qs : { ...

Utilize Object.keys and Object.values to transform a JSON object into a ChartJS representation

I have a unique JSON file structure that I am trying to display in ChartJS. The data looks like this: { "AAPL": [ { "Q1": -26986, "Q2": -168099, "Q3": -137101, "Q4": -5 ...

How to Deactivate Navigation Tabs in AnythingSlider?

I am encountering some issues with the css and js while using the AnythingSlider tool. Specifically, I want to modify the navigation tabs in a way that certain tabs will either remain unchanged or become inactive based on a ColdFusion conditional. For ins ...

Leveraging .Net Variables for Sending Event Tracking in Google Analytics.js

I am facing an issue while trying to send Event Tracking values with labels set by variables in the code behind. Although everything renders correctly on the page, the events are not being tracked. The dynamic events are not showing up in Google Analytics ...

Unable to switch between navigation items and icons

Currently, I am in the process of learning vanilla JavaScript and I'm trying to incorporate a navigation feature similar to when the hamburger icon is clicked. However, I have encountered an issue where I cannot toggle the hamburger icon to change it ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

The anchor links fail to navigate to specific page sections when refreshing the browser or navigating back and forth

I've created a webpage using HTML that contains links within the page. <div> <a href="#first">first</a> <a href="#second">second</a> <div id="first">First div</div> <div id="second">Second div</div&g ...

learn how to implement local storage for a to-do list application using JavaScript

How do I implement the storage property in this code snippet? The current code is not functioning correctly and resets after each page refresh. Please review my code at the following link: https://jsfiddle.net/74qxgonh/ let values = []; // Accessing Form ...

Using Jquery to show element when <select> is updated

I've been struggling to make this work due to my limited jquery/js skills. My goal is to have a different message displayed for each option selected from the dropdown menu for further information. <label class="checklabel">Is it possible to re ...

An illustration using Three.js

Could someone please guide me on extracting the threejs.org example showcased at this URL: . ...

Extracting the route path without parameters in Vue Router interceptors - is it possible?

I am trying to extract the base path of a route in my Vue Router interceptor without including its parameters. router.beforeEach((to, from, next) => { console.log(to); }) For example, if the route is /profile/abc/def where abc and def are dynamic ...