Tips for utilizing the track OrbitControls in three.js

Presently, there are two blocks visible within the space:

const material1 = new THREE.MeshBasicMaterial({color: '#00ff00'});
const cube1 = new THREE.Mesh(geometry, material1);
cube1.position.set(0, 0, 0);

const material2 = new THREE.MeshBasicMaterial({color: '#ffff00'});
const cube2 = new THREE.Mesh(geometry, material1);
cube1.position.set(-3, 0, 0);

The initial cube (green) is situated at the center position of the screen, with the second cube (yellow) offset by -3 along the X-axis.

To witness the yellow cube rotating around the green cube, click and drag the left mouse button. This showcases the OrbitControls feature in action.

The current desired action involves rotating the green cube around the yellow cube. In order to achieve this, I tried utilizing the statement: control.target=cube2.position; While this does meet the requirements, it inadvertently pulls the yellow cube back to the original position.

Needless to say, this outcome is not the intended effect. Could someone kindly advise me on how to rectify this issue?

Thank you in advance!

Access the code here

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

<template>
  <div ref="container" style="width: 100%; height: 100%"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import * as THREE from "three";
// Orbit Controller
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const container = ref(null);

// Scene, Camera, Renderer, Orbit Controller, and Models
let scene, camera, renderer, control, cube1, cube2;
let axesHelper1, axesHelper2, gridHelper;

onMounted(() => {
  init();
  animate();

  // Listen for window resizing
  window.addEventListener("resize", () => {
    // Modify renderer aspect ratio
    renderer.setSize(window.innerWidth, window.innerHeight);
    // Update camera aspect ratio
    camera.aspect = window.innerWidth / window.innerHeight;
    // Update camera projection matrix
    camera.updateProjectionMatrix();
  });
});

// Scene setup
function initScene() {
  scene = new THREE.Scene();
}
// Camera setup
function initCamera() {
  camera = new THREE.PerspectiveCamera(
    30,
    window.innerWidth / window.innerHeight,
    1,
    5000,
  );
  camera.position.z = 20;
  scene.add(camera);
}
// Orbit Controller setup
function initControl() {
  control = new OrbitControls(camera, renderer.domElement);
  // Set damping
  control.enableDamping = true;
  control.dampingFactor = 0.05;
}
// Renderer setup
function initRenderer() {
  // Create renderer with antialiasing
  renderer = new THREE.WebGLRenderer({ antialias: true });
  // Set size
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Set pixel ratio
  renderer.setPixelRatio(window.devicePixelRatio);
  container.value.appendChild(renderer.domElement);
}

// Model setup
function initModel() {
  const geometry = new THREE.BoxGeometry(1, 1, 1);

  // Initial cube
  const material1 = new THREE.MeshBasicMaterial({ color: "#00ff00" });
  cube1 = new THREE.Mesh(geometry, material1);
  cube1.position.set(0, 0, 0);
  axesHelper1 = new THREE.AxesHelper(2);
  cube1.add(axesHelper1);
  scene.add(cube1);

  // Second cube
  const material2 = new THREE.MeshBasicMaterial({ color: "#ffff00" });
  cube2 = new THREE.Mesh(geometry, material2);
  cube2.position.set(-5, 0, 0);
  axesHelper2 = new THREE.AxesHelper(2);
  cube2.add(axesHelper2);
  scene.add(cube2);

  // Grid helper
  gridHelper = new THREE.GridHelper(10, 10);
  scene.add(gridHelper);
}

function init() {
  // Scene
  initScene();
  // Camera
  initCamera();
  // Renderer
  initRenderer();
  // Orbit Controller
  initControl();
  // Models
  initModel();
}
function animate() {
  requestAnimationFrame(() => {
    animate();
  });

  control.update();

  // Render scene
  renderer.render(scene, camera);
}
</script>
<style scoped></style>

Answer №1

Perhaps I have grasped the concept now...

If you wish to rotate it on its own, you can incorporate a simple animation, although I assume you're already aware of that.

function animate() {
  requestAnimationFrame(animate);
  cube2.rotation.y += 0.05;

  control.update();
  renderer.render(scene, camera);
}

Therefore, you might be interested in applying that rotation based on mouse movement or something similar

function initControl() {
  control = new OrbitControls(camera, renderer.domElement);
  // Set damping
  control.enableDamping = true;
  control.dampingFactor = 0.05;
// Add listener
  control.addEventListener("change", onControlChange);
}
//---------
function animate() {
  requestAnimationFrame(() => {
    animate();
  });

  control.update();
  renderer.render(scene, camera);
}
function onControlChange() {
  // If you want to adjust the x-axis as well
  // cube2.rotation.x = control.getPolarAngle();
  cube2.rotation.y = control.getAzimuthalAngle();
  renderer.render(scene, camera);
}

You have the option to utilize GSAP or Anime if desired

function animate() {
  requestAnimationFrame(animate);
  control.update();
  renderer.render(scene, camera);
}
function onControlChange() {
  gsap.to(cube2.rotation, { y: control.getAzimuthalAngle(), duration: 0.5 });
  renderer.render(scene, camera);
}

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

Having trouble with a link not working correctly after concealing the file extension with htaccess?

I've configured the ht-access file to hide the .php file extension. Here's the code inside the .htaccess file: # Apache Rewrite Rules <IfModule mod_rewrite.c> Options +FollowSymLinks RewriteEngine On RewriteBase / # Add trailing slash to U ...

What is the best way to convert a deeply nested PHP array/object into JSON format?

For those who want a shorter explanation, here it is: I have a JavaScript array filled with objects. Some properties of these objects contain arrays of objects, which in turn may have more arrays or objects nested within them. This results in 5 levels of n ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

Steps to designate a character depending on the frequency of its duplication within an array

I have a series of values in an array that I need to go through and assign incremental numerical values, starting from 1. If the same value appears more than once in the array, I want to append the original assigned number with the letter A, and then B, ac ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Are the Bootstrap columns arranged in a vertical stack instead of side by side?

I currently have two large columns that are stacked vertically on top of one another. I want them to be side by side, like | 1 | 2 |, so that the user can view both columns simultaneously. I am seeking tips or suggestions on how to resolve this issue. Whil ...

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

Is there a way to conclude an Inquirer prompt depending on the response received?

My current project involves creating an application that presents a series of questions to gather information and generate an employee profile. This application is designed to be recursive, meaning that users will have the option to exit and terminate the ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Displaying selected list item while concealing the original

I have a dropdown menu with several options. What I am looking for is to have it so that when we click on the drop down, a list of choices appears. Then, when we select an option from the dropdown, the original selection should be replaced with the one th ...

Building a 3D Earth model using three.js for WebGL applications

I found a code online, but it doesn't seem to work. Can someone provide me with the HTML code needed to make it run in my browser? The original code was sourced from this website (github repository) Github code repository https://github.com/turban/ ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

Get rid of the title on Superfish Menu in Drupal 7

Exploring Drupal for the first time, I've been able to find solutions to all my queries except one - removing the "Main Menu" header from my superfish menu. The region called superfish has successfully had superfish added to it, but I'm unable t ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...