Using three.js to maintain an object's position on top of another object's surface

I have created a terrain geometry using this JavaScript code:

     var geometry = new THREE.PlaneGeometry(100, 100, 100 , 100 );
     for (var i = 0, l = geometry.vertices.length; i < l; i++) {
          geometry.vertices[i].z  = Math.random() / 2;
     }
     geometry.computeFaceNormals();
     floor = new THREE.Mesh(geometry, floorMaterial);

Now, I have another object3d that needs to move on the surface of this terrain. How can I determine the elevation difference my object needs to adjust, possibly using raycasting?

[Edited] I have successfully addressed the first part, however, I am facing an issue with the raycaster. The distance returned by the raycaster seems to be incorrect, as it is flipped for each face. Here is an example to demonstrate this:

Answer №1

Indeed, the THREE.Raycaster is expected to function correctly, as you had suspected.

During the update loop, it is necessary to cast rays in a downward direction.

var raycaster = new THREE.Raycaster();
raycaster.set(yourMovingObject.position, THREE.Vector3(0, -1, 0));

Subsequently, you must specify a distance from the ground where the object should cease "falling".

var distance = 40; //adjust to fit your specific requirements

Lastly, ensure to examine the intersections.

var velocity = new THREE.Vector3();

var intersects = raycaster.intersectObject(floor); //use intersectObjects() to check for intersections with multiple objects

//If the new position is higher, move the object upwards
if (distance > intersects[0].distance) {        
    yourMovingObject.position.y += (distance - intersects[0].distance) - 1; //including the -1 to address a shaking issue
}

//Apply gravity and prevent falling through the floor
if (distance >= intersects[0].distance && velocity.y <= 0) {
    velocity.y = 0;
} else if (distance <= intersects[0].distance && velocity.y === 0) {
    velocity.y -= delta ;
}

yourMovingObject.translateY(velocity.y);

Implementing something along these lines should prove effective, although adjustments will likely be necessary to suit your specific environment.

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

Making a call to a recently generated document in Firestore

After adding a new document, how do I access its data property? For instance: https://firebase.google.com/docs/firestore/manage-data/add-data // Add a new document with a generated id. let addDoc = db.collection('cities').add({ name: 'To ...

Error: AJAX encountered an unexpected token

An error message has appeared stating: Uncaught SyntaxError: Unexpected token : This error relates to the following line of code: data: userCoupon: $('#couponCode').val(), Here is the script in question: $(function() { $("#signInButton2"). ...

Is webpack necessary for segregating dependencies during installation?

Currently, I'm diving into a tutorial on webpack and it's been three days already, but confusion still reigns! I am delving into the commands: npm i webpack --save-dev I find myself puzzled by the '--save-dev' in the above command whi ...

Utilizing AJAX to seamlessly transfer id elements to a database

I have the following working code: <script> function displayUserData(str) { if (str=="") { document.getElementById("userDetails").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLH ...

Tips for incorporating an entire JavaScript file into a React JS project

I'm facing an issue with a .js file (JavaScript file) that lacks exports code, containing only a constructor and some prototype methods. I am trying to incorporate this file into my ReactJS App. My approach involved adding a script tag in client/inde ...

JavaScript Plugins for Cordova

The more I delve into the inner workings of Cordova, the clearer it becomes to me. Yet, one area that continues to perplex me is the structure of JavaScript plugins. Typically, I write my JavaScript code as follows, adhering to what I believe is the stand ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

Monitor fetch() API calls and responses in JavaScript

I’m looking to intercept fetch API requests and responses using JavaScript. Specifically, I want to be able to capture the request URL before it is sent and also intercept the response once it has been received. The code below demonstrates how to inter ...

Reorganize JSON data in JavaScript

I am in the process of creating a tree structure, and I want it to be organized in the order of name, desc, then children. However, the JSON data I have received is not in this order. Is there a way to rearrange it efficiently or perhaps optimize the code ...

The 'onChange' event in React is being triggered only once

Currently utilizing material-ui Library Below is my React component: import Checkbox from '@material-ui/core/Checkbox'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import React from "react"; import { withStyles ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

Issue with activating a Modal through a button inside a table row on React

I'm currently working on two files: Modal.js and Users.js. Users.js features a table with an API get query linked to it, and in the last column of the table, there's a dropdown for each row that contains three buttons: View, Edit, and Delete. My ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...

Upon loading the page, the menu automatically drops down for easy navigation

Currently, I am working on a WordPress site using the WallBase theme. You can check out a preview of the theme here. One issue I am facing is that when the page fully loads, the menu automatically drops down. I have tried various solutions to keep the me ...

Struggling to configure Velocity Js?

After attempting to use Velocity Js for the first time, I encountered some issues while trying to create a navigation menu. Despite having functioning code and animations, the menu failed to open. I followed the instructions on the Velocity JS site by incl ...

The HTML code may fade away, but the JavaScript is still up and running behind the

Switching between different div elements in my HTML document is a challenge. Here's the code I currently have: <div id="screen1" class="current"> <div id="press_any_key_to_continue"> <font style="font-family: verdana" color="yellow ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

An alternative approach to coding

I am a JavaScript developer who writes code to handle multiple keys being pressed simultaneously. The current implementation involves checking each key's keyCode individually, which I find cumbersome. var key = event.keyCode; if (key === 39 { / ...

What is the reason for the malfunction in the login dialog?

I'm having trouble implementing AJAX login functionality on my website. When I click the submit button, nothing seems to happen. Can someone take a look at the code and help me out? $(document).ready(function() { var user, pass; function login(us ...

Utilizing helper functions in Node based on their specific types

In my helper module, I have different files like content, user, etc. These files define various helpers that can be used in the router. Below is the code for the router: router.js var helper = require("./helper"); function index(response) { response ...