Reposition TorusGeometry to align with Coplanar Points

My three.js scene consists of 3 coplanar points and a torus geometry. I am looking for a way to transform the torus geometry so that it appears to be resting on the coplanar points. How can this be achieved in three.js?

You can view an example of this scenario in action on this codesandbox.

https://i.sstatic.net/ZvaHh.png

Answer №1

Understanding your requirement, you can utilize the .lookAt() method in combination with THREE.Plane() and its .normal property to achieve the desired outcome:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.z = 2.5;
const renderer = new THREE.WebGLRenderer({
  antialias: true
});
const controls = new THREE.OrbitControls(camera, renderer.domElement);

const ambientLight = new THREE.AmbientLight(0x888888);
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xfdfcf0, 1);
directionalLight.position.set(10, 10, 10);
scene.add(directionalLight);

renderer.setClearColor("#000000");
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const positionFrom = (latitude, longitude, radius) => {
  const phi = (90 - latitude) * (Math.PI / 180);
  const theta = (longitude + 180) * (Math.PI / 180);
  const x = -(radius * Math.sin(phi) * Math.cos(theta));
  const z = radius * Math.sin(phi) * Math.sin(theta);
  const y = radius * Math.cos(phi);
  return [x, y, z];
};
const points = [
  ["80.9721379481747", "-93.2620712575402"],
  ["84.899876841301", "-15.8849444339213"],
  ["-80.9618531929051", "81.2440393281301"]
];
const pts = [];
points.forEach(([lat, long]) => {
  const position = positionFrom(lat, long, 1);
  const earthGeometry = new THREE.SphereGeometry(0.1, 0.1, 0.1);
  const earthMaterial = new THREE.MeshPhongMaterial({
    color: 0xffffff
  });
  const earth = new THREE.Mesh(earthGeometry, earthMaterial);
  earth.position.set(...position);
  scene.add(earth);
  pts.push(earth.position);
});

const plane = new THREE.Plane();
plane.setFromCoplanarPoints(pts[0], pts[1], pts[2]);
const helper = new THREE.PlaneHelper(plane, 1, 0x00ff00);
const torusGeometry = new THREE.TorusGeometry(0.5, 0.1, 3, 100);
const torusMaterial = new THREE.MeshBasicMaterial({
  color: 0x00e1ff
});
const torus = new THREE.Mesh(torusGeometry, torusMaterial);
torus.lookAt(new THREE.Vector3().addVectors(torus.position, plane.normal));
scene.add(helper);
scene.add(torus);

var render = function() {
  requestAnimationFrame(render);
  controls.update();
  renderer.render(scene, camera);
};

render();
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.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

Is it possible to include a JavaScript file in another JavaScript file synchronously?

Is there a way to import external JavaScript files into my HTML file without causing any issues? Similar to how @import works in CSS. I've seen suggestions like appending a script tag to the DOM on websites like StackOverflow, but this method loads t ...

The drop-down menu keeps flickering instead of remaining open when clicked

I am facing an issue with a dropdown menu in my webpage. The menu is initially hidden, but should become visible when the list element containing it is clicked. I have written JavaScript code to add a class that changes the visibility property to visible u ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...

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 ...

Updating the functionality of Bootstrap 4 accordions

Utilizing HTML templates based on Bootstrap 4.3.1, I am delivering educational content to my students. In the current setup, all accordion panels are closed when the page loads, and each panel can be opened independently of others. To see a live example, ...

Tips for adjusting the file name and extension when saving a text file from a data URI

When I try to download data using a Data URI (this method works in Chrome and Firefox), I use the following code: url1 = "data:attachment/plain;base64,encodeuri(<base64data-xyz>)" By specifying the MIME type as attachment, it forces the file to dow ...

Tips on how to patiently wait until the database connection is established and all queries are successfully executed for every database specified in an array

A file containing JSON data with database details needs to execute a series of queries for each database connection. The map function is currently waiting for the database connection. Below is the start function function start() { console.log('func ...

What is the correct way to transfer a function from a component.ts file to a service file?

I recently wrote a function in my component.ts file that sends a PUT request. It was working perfectly fine, but I decided to refactor and move the function to a service.ts file. After moving it, the functionality seems to have broken. Whenever I click on ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

Unable to access style property, encountering error on separate page

Once again, I'm feeling a bit lost on where to go with this coding issue. It seems quite basic, but I'm struggling to pinpoint the problem. My goal is to hide several IDs, and while it does work, I keep encountering an error: Uncaught TypeError: ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

ways to modify hash URLs using JavaScript

I am looking to add separate hash links for my Facebook and Instagram social media pages. I also want to change the text color to blue for Facebook and yellow for Instagram. How can I achieve this using JavaScript? let socialMediaData = [{ s_media: &apo ...

experiencing challenges with jQuery event handlers in version 1.6, but not encountering the same issues in newer releases

Presently, I am using a version 1.6 of the Jquery library, which takes time to update. I am attempting to incorporate a Jquery event handler. I have a collection of divs that contain many buttons. These buttons are constantly being added dynamically, and ...

What is the functionality of a nested child directive root element when placed at the same level as the parent directive root element?

Hello there, I'm currently facing a unique situation that has me stumped. Is it possible to replace the content of a directive's root element with that of a nested (child) directive? Here is an example scenario: <div id=”main”> <n ...

I am experiencing issues with my CSS list style, as it seems to be functioning fine on all other elements except for

Can anyone provide assistance in troubleshooting why my CSS is not functioning properly? How can I ensure it links with my external CSS file for the list to display correctly? The issue seems to arise when using external CSS rather than internal. Whenever ...

A variety of products combined into a single form

I am looking to enhance my form by allowing users to add multiple entries before submitting, similar to an "add to cart" feature. The added entries should be displayed on the same page in a separate div along with a submit button. Once the user is ready, t ...

The click function for the responsive navbar hamburger is not functioning properly

Having some trouble with the code not working in responsive mode. I've tested it on a 600px screen and the hamburger button doesn't seem to work (I click it and nothing happens). I've gone through both the CSS and JS multiple times but can&a ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...

The constant frustration of trying to extract a predefined AJAX return value, only to

My Ajax call and PHP function are causing an issue in Firefox. Despite receiving an HTTP 200 status, the response shows the value "false," but it is not being passed to the success part of the Ajax handler - instead, I always get undefined. I have plenty ...