Issues encountered when using Three.js raycasting to position objects above a plane

My heightmap-based plane is not working with raycasting, and I'm also having trouble placing an object above the hovered triangle.

UPDATE: By commenting out the height section (pgeo.vertices[i].z = heightmap[i] * 5;), it seems to work inconsistently. The highlighting appears sometimes depending on the camera angle. Zooming in or out causes the triangle to disappear and reappear unpredictably.

I used the voxelpainter example as a basis for this jsfiddle:

http://jsfiddle.net/waf6u7xp/1/

However, I'm unsure if there's a better way to determine the hovered triangle. Maybe projection based on the heightmap would be more effective? Any suggestions?

This is the code responsible for the raycast:

function onDocumentMouseMove( event ) {

    event.preventDefault();

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

    var vector = new THREE.Vector3( mouse2D.x, mouse2D.y, camera.near );
    projector.unprojectVector( vector, camera );

    var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    var intersects = raycaster.intersectObjects(objects);

    // Toggle rotation bool for meshes that we clicked
    if ( intersects.length > 0 ) {

        var match = intersects[0];

        console.log(match);
        selectedTile = match.faceIndex;
        var f = face = match.face;
        var faceIdx = match.faceIndex;
        var faces = match.object.geometry.faces;
        var vertices = match.object.geometry.vertices;


        var fa = vertices[f.a];
        var fb = vertices[f.b];
        var fc = vertices[f.c];


        var a = fa.clone();
        var b = fb.clone();
        var c = fc.clone();

        highlightpla.geometry.vertices[0].setX(Math.ceil(a.x));
        highlightpla.geometry.vertices[0].setY(Math.ceil(a.y));
        highlightpla.geometry.vertices[0].setZ(a.z+1);
        highlightpla.geometry.vertices[1].setX(Math.ceil(b.x));
        highlightpla.geometry.vertices[1].setY(Math.ceil(b.y));
        highlightpla.geometry.vertices[1].setZ(b.z+1);
        highlightpla.geometry.vertices[2].setX(Math.ceil(c.x));
        highlightpla.geometry.vertices[2].setY(Math.ceil(c.y));
        highlightpla.geometry.vertices[2].setZ(c.z+1);
    }
}

Answer №1

After some investigation, I managed to pinpoint the issue you were facing.

Although your code is functional, there is a minor problem that needs to be addressed. It appears that the heightmap array contains only 2493 points, causing the point geometry to be incompatible with the dimensions of 127 x 127

To resolve this, you simply need to adjust the widthSegments and heightSegments parameters in your PlaneGeometry constructor to match the number of points.

Here is the corrected code:

var size = Math.floor( Math.sqrt( heightmap.length ) ) - 1;
var pgeo = new THREE.PlaneGeometry( 16384/2, 16384/2, size, size );

With these modifications, everything should work smoothly...

Feel free to check out the updated demonstration here

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

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Is there a way to retrieve the timestamp of a DOM change event when using MutationObserver for event tracking?

Currently, I am successfully using MutationObserver to monitor changes in the DOM. However, I would like to include a timestamp for each event. Unfortunately, there doesn't seem to be a timestamp property available in the MutationRecord. https://deve ...

- The click function is failing to work after an ajax call [Potential event delegation problem]

I have a webpage where I update the contents of an unordered list using $.get() every 5 seconds. The issue I am facing is that the click function for the list items is not working properly. Even though the list items are being updated correctly, there se ...

Unable to make changes to the AWS Dynamo array

I am currently attempting to update a JSON array. I have a table in DynamoDB where I successfully inserted the JSON data using the PUT method. Partition key : _id , Type : S Below is the JSON data that has been saved into the database: { "_id": ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

What is the best approach for transmitting data to the post method of Node.js using AJAX/jQuery?

A UDP server I have is set up to respond with a different message each time it receives a message. When I hard code the message into the variable "message," everything works fine. However, I want the client to be able to manually type in a message, and t ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Best Way to Eliminate "#" Symbol from URL Address in UI-Router

My website URL is structured as follows: This is the index page where I utilize Angular UI-Router to navigate to different views, however, the URL retains the hash symbol (#) like this: Query: I am looking for a way to eliminate/remove the hash tag from ...

Implementing an event listener on an anchor element dynamically inserted through Javascript

I made an Ajax call that retrieves a list of movie titles. I am trying to click on a button next to each title in order to add it to my "currently watching" list. However, my "add" link is not responding to the event handler. What steps can I take to suc ...

The error message that you are seeing is indicating that the `contracts` property of `this.state

Despite having encountered this issue before, I am still struggling to find a solution. The code snippet for fetching data is as follows: async componentDidMount(){ try { const res = await fetch('https://example.com/data.json'); ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

Managing redirects in CodeIgniter 3

I have encountered an issue while using Codeigniter 3. When I submit a form, the validate function name appears in the URL before being redirected to another page. How can I hide the validate function name in the URL during submission? Here's a sampl ...

The ES6 method of binding click handlers with parameters in React

After reading numerous articles on the usage of () => {} syntax, binding in the constructor, and binding in the props, I have come to understand that binding this can be performance-intensive. Furthermore, automatic binding with arrow functions incurs a ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Enhance the vertices and faces in three.js

Our team utilizes threejs for developing complex 3D scenes in WebGL, often encountering geometries with tens of thousands to hundreds of thousands of vertices. These geometries are constructed using basic threejs geometries such as Spheres and TubeGeometry ...

What is the best way to retrieve the ajax response using Ajax.Responders in prototype.js?

I am looking to retrieve the response of each Ajax call within the function below Ajax.Responders.register({ onCreate: function() { }, onComplete: function(transport) { }, onSuccess: function(transport) { }, }); ...

What is the best way to merge two foursquare requests into one?

I'm a newcomer here trying to work with the FourSquare API. I'm not entirely confident in my approach, but I am attempting to retrieve data from a search using "". However, I also want to gather more details about each venue, such as their hours ...

Editing rows directly within the ng table interface

Hey there, I'm currently working on implementing inline row editing using ng table After clicking the edit icon and changing values, I encounter an error upon clicking the save icon: TypeError: Cannot read property 'untrack' of undefined ...