Adjust the position of vertices when the mouse hovers over them

I have a PlaneGeometry and I am trying to adjust the z position of the vertex being hovered over, but I am uncertain about how to retrieve it.

//THREE.WebGLRenderer 69

// Creating plane
var geometryPlane = new THREE.PlaneGeometry( 100, 100, 20, 10 );

for (var vertIndex = 0; vertIndex < geometryPlane.vertices.length; vertIndex++) {
    geometryPlane.vertices[vertIndex].z += Math.random();
}
geometryPlane.dynamic = true;
geometryPlane.computeFaceNormals();
geometryPlane.normalsNeedUpdate = true;
var materialPlane = new THREE.MeshLambertMaterial( {
    color: 0xffff00,
    side: THREE.DoubleSide,
    shading: THREE.FlatShading,
    overdraw: 0.5,
    vertexColors: THREE.FaceColors
} );
plane = new THREE.Mesh( geometryPlane, materialPlane );
plane.geometry.colorsNeedUpdate = true;

// Mouse event
container[0].addEventListener( 'mousemove', onMouseMove, false );
function onMouseMove( event ) {
    var mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
    var mouseY = -( event.clientY / window.innerHeight ) * 2 + 1;

    var vector = new THREE.Vector3( mouseX, mouseY, camera.near );
    vector.unproject( camera );

    raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

    if ( intersects.length > 0 ) {
        // Adjust the z position of the selected vertex
        var selectedVertex = ???
        selectedVertex.position.z +=5;
    }
} 

Answer №1

When dealing with a single vertex rather than the entire object, consider following these steps:
1- Locate the intersecting face in intersects[0].face
2- The face likely consists of 3 vertices (most likely a THREE.Face3): Identify the nearest vertex V that aligns with the intersection point intersects[0].point.
3- Adjust the z-coordinate of vertex V accordingly.

This approach is merely a suggestion and may not be foolproof... ;)

Answer №2

To adjust the Z position of the intersected object, you can utilize the following method:

intersects[0].object.position.z+=10;

You can examine the code snippet below for a demonstration and to view the code.

var container, stats;
var camera, scene, raycaster, renderer;

var mouse = new THREE.Vector2(),
    INTERSECTED;
var radius = 100,
    theta = 0;

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 = '<a href="http://threejs.org" target="_blank">three.js</a> webgl - interactive cubes';
    container.appendChild(info);

    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);

    scene = new THREE.Scene();

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

    var geometry = new THREE.PlaneGeometry (50, 50, 50);

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

        var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
            color: Math.random() * 0xffffff
        }));

        object.position.x = Math.random() * 800 - 400;
        object.position.y = Math.random() * 800 - 400;
        object.position.z = Math.random() * 800 - 400;

        object.rotation.x = Math.random() * 2 * Math.PI;
        object.rotation.y = Math.random() * 2 * Math.PI;
        object.rotation.z = Math.random() * 2 * Math.PI;

        object.scale.x = Math.random() + 0.5;
        object.scale.y = Math.random() + 0.5;
        object.scale.z = Math.random() + 0.5;

        scene.add(object);

    }

    raycaster = new THREE.Raycaster();

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xf0f0f0);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.sortObjects = false;
    container.appendChild(renderer.domElement);

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

    document.addEventListener('mousemove', onDocumentMouseMove, false);

    //

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

}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);

}

function onDocumentMouseMove(event) {

    event.preventDefault();

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

}

//

function animate() {

    requestAnimationFrame(animate);

    render();
    stats.update();

}

function render() {



    // find intersections

    var vector = new THREE.Vector3(mouse.x, mouse.y, 1).unproject(camera);

    raycaster.set(camera.position, vector.sub(camera.position).normalize());

    var intersects = raycaster.intersectObjects(scene.children);


    if (intersects.length > 0) {

        if (INTERSECTED != intersects[0].object) {
            console.log(intersects[0].point);
             console.log(intersects[0].object.position);

            if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
             /*******************************************************************/   
/// You can modify the Z position as demonstrated below
            
   intersects[0].object.position.z+=10;
/********************************************************************/
            

            INTERSECTED = intersects[0].object;
            INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
            INTERSECTED.material.emissive.setHex(0xff0000);
            

        }

    } else {

        if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);

        INTERSECTED = null;

    }

    renderer.render(scene, camera);

}
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r69/three.min.js"></script>

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

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

Ways to navigate to a new page using jQuery Mobile

As a newcomer to jquery mobile, I am still learning how ajax handles page transitions, and I suspect the issue may be related to that. In my jqm / phonegap app, I have set up multiple pages. The homepage checks if the user is logged in by retrieving membe ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

Integrating a parameter into a plugin allows for displaying a specified number of elements in the output

A unique plugin is being used to create a vertical slideshow effect. This plugin scrolls the top-most div in a series of divs with the same class upwards, removes it from the container, and appends it to the bottom of the series within the container. The e ...

Error encountered in 11ty: Invalid operation - eleventyConfig.addPassthroughCopy is not a recognized function

Attempting to integrate my CSS and JavaScript codes into 11ty has been a bit challenging for me. I recently discovered that 11ty utilizes something called .11ty.js, so I decided to utilize the addPassthroughCopy() function. Below is the script I tried: mo ...

Customize the appearance of your apps script using conditional formatting to highlight values that are

https://i.stack.imgur.com/L1KFZ.png I need to create an array of all 50 US states based on the abbreviations in a column. The goal is to compare each cell against the array and if it doesn't match, format it red. After researching conditional format ...

Ways to attach jQuery live to the entire window?

tag: I want to trigger specific functions whenever the mouse moves, regardless of its position on the browser window. Currently, I am using the following code snippet: $('html').on('mousemove', function(e) { ... } However, this appr ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

Do two Express JS applications run on separate threads?

Running two express apps on different ports raises the question of whether they assign themselves to different cores, knowing that express typically runs on a single thread. The cluster module, however, replicates the express app and allows them to utiliz ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

Stepper wizard experiences a variation in CSS styling when minified

Two plunkers showcasing material design wizard selectors are causing different behavior upon stepper clicks. One uses a minified version of CSS while the other is expanded. The issue arises with the transition effects in the .step-wizard .progressbar class ...

JavaScript: A guide to solving systems of equations

I'm attempting to perform algebraic operations in JavaScript using certain conditions and known variables. However, I lack proficiency in mathematics as well as JavaScript to comprehend how to articulate it. Here are the conditions: var w1 = h1/1.98 ...

The file always fails the Regex test in Node.js

I am dealing with a log file that contains lines structured like this: [Thu Mar 30 2017 11:24:51 GMT+0100 (WEST)] {"serial":"CA-2M-1107619","type":"iface","body":{"action":"up","device":"tun_man","ip":"127.255.0.10","ip6":"2016:900d:c0de::1001"} My goal ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

When using the jQuery datepicker on dynamically generated input fields, the selected date automatically updates the first input field

I am currently integrating date inputs with attached datepicker functionality. The issue I am facing is that when I select a date in the first input and proceed to pick another date in the second or subsequent inputs, the last selected date appears in the ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

Create a new form based on the current mesh appearance

Can shape be extracted from a mesh object? I have a THREE.mesh object that was created using vectors, and I want to convert or duplicate one side of the object into a shape in order to apply some extrude effects to it. :) ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...