Spinning a 3-dimensional vector in THREE.js using dual axes

Apologies for potentially posting a duplicate question.

I am working with two 3D vectors:

Center: (0, 0, 0)

Orb: (0, 0, 100)

My goal is to rotate the orb-vector around the center-vector on both the X and Y axes to ensure an object is always in view of the camera in the direction it's facing.

I have attempted the following code with no success:

var vector = new THREE.Vector3(0, 0, 100);
vector.applyAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI * 0.5);
vector.applyAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI * 0.5);
orbBall.position.copy(vector);

Answer №1

"My goal is to keep an object always in view of the camera, facing in its direction."

If you want to ensure that the object orbBall always faces the camera and both are part of the THREE scene, you can simply use lookAt like this:

orbBall.lookAt(camera.position);

If you need to align a specific side of orbBall, you can use a null dummy Object3D to achieve this. Add the dummy node to the scene, then add orbBall to the dummy, like this:

dummy = new THREE.Object3D();
scene.add(camera);
scene.add(dummy);
dummy.add(orbBall);
// ... code to align dummy+orbBall
dummy.lookAt(camera.position);
// ... you can then rotate orbBall around inside dummy as needed

Answer №2

Upon deep investigation into this matter, I've come to realize that it involves some complex mathematics. If you're interested, I recommend watching this lecture on quaternions:

https://www.youtube.com/watch?v=mHVwd8gYLnI

Following @bjorke's advice, I employed a dummy object and it worked like a charm.

var container, scene, camera, renderer, controls, stats;
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(100, 100, 400);
camera.lookAt(scene.position);
scene.add(camera);

renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );

var light = new THREE.DirectionalLight(0xffffff); //new THREE.PointLight(0xffffff);
light.position.set( 30, 80, -15 );
scene.add(light);


var boxGeo = new THREE.BoxGeometry( 10, 10, 10);
var axes = new THREE.AxisHelper(1000);
scene.add( axes );

var cameraObj = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x888800}));
scene.add(cameraObj);

var orbSpace = new THREE.Object3D();
scene.add(orbSpace);
var orbBall = new THREE.Mesh(boxGeo, new THREE.MeshLambertMaterial( {color: 0x880088}));
orbBall.position.set(0, 0, cameraObj.position.z + 100);
orbSpace.add(orbBall);

animate();

var camX = 0.3;
var camY = 0;
function animate() {

    requestAnimationFrame( animate );

    camY += 0.02;
    if (camY >= 2) camY = 0;

    cameraObj.rotation.x = Math.PI * document.querySelector('#volume').value;
    cameraObj.rotation.y = Math.PI * camY;
    orbSpace.position.copy(cameraObj.position);
    orbSpace.rotation.copy(cameraObj.rotation)


    renderer.render( scene, camera );

}

If you're curious about how it operates, check out this codepen:

http://codepen.io/arpo/pen/RrpMJJ

You can adjust the X angle in the upper right corner

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

Learn the process of extracting data from dynamically generated elements in JavaScript

I am a beginner in Javascript and Jquery and have recently started exploring business rules with Chris Powers. https://github.com/chrisjpowers/business-rules My current project involves adding a range slider for numbers and a number spinner. I attempted us ...

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

Navigating to a parent URL where the Angular configuration is set can be achieved by following these steps

My application revolves around a webpage created with the use of node and angular. On the root URL (/), I have incorporated a signup and login form without the use of Angular. Upon successful login, Angular scripts and configuration files are loaded on the ...

Unable to trigger the show_popup function by clicking the button

Why won't this piece of code function as expected? <script src="web_push.js"></script> <body> <button onclick="show_popup()"> Button </button> </body> The content of web_push.js file is shown below ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Can you explain the process of a put request in Angular, Express, and Mongoose?

My colleague and I are currently deciphering the inner workings of a code snippet generated by a tutorial. Our main focus is on how the client/server communication flows once line 8 of factory.js is triggered: factory.js app.factory('postFactory&apo ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...

Steps for retrieving user information post authentication query:1. Begin by initiating the query to authenticate the

This is my script.js file var express = require('express'); var router = express.Router(); var expressValidator = require('express-validator'); var passport = require('passport'); const bcrypt = require('bcrypt'); c ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

What is the best way to keep JWT secure in a web browser?

Recently, I delved into the world of JSON Web Tokens (JWT) for the first time. I'm currently working on a Node.js application utilizing the Hydra-Express framework. My goal is to implement JWT for authentication purposes. Following the documentation, ...

Utilize morris.js within an AngularJS directive to handle undefined data

Using the morris.js charts in my angular js app has been a great addition. I decided to convert it into a directive for better organization and functionality: barchart.js: angular.module('app_name').directive('barchart', function () ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...

What is the best way to select multiple items using mongoose?

For instance, consider this list: [ { name: "John" }, { name: "Mike" }, { name: "Homer" }, { name: "Bart" }, { name: "Dmitry" }, { name: "Dan" } ] If I want to select specific objects ...

having difficulty implementing the blur effect in reactJS

Currently, I am working on developing a login page for my project. Below is the code snippet I have implemented for the functionality: import React, { useState, createRef } from "react"; import { Spinner } from "react-bootstrap"; import ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Using JavaScript regex to split text by line breaks

What is the best way to split a long string of text into individual lines? And why does this code snippet return "line1" twice? /^(.*?)$/mg.exec('line1\r\nline2\r\n'); ["line1", "line1"] By enabling the multi-line modifi ...

Connect an EventListener in JavaScript to update the currentTime of an HTML5 media element

*update I have made some changes to my code and it is now working. Here's the link: I am trying to pass a JavaScript variable to an HTML link... You can find my original question here: HTML5 video get currentTime not working with media events javscr ...

Constantly monitoring the current window width

Is there a way to dynamically get the width of the browser as it is resized in real time? I have found a solution that provides the width, but it only updates when I refresh the page. How can I continuously update the value while resizing the browser? Thi ...

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

Contrast two items with identical keys arranged differently

let firstObject = { key1: value1, key2: value2 } let secondObject = { key2: value2, key1: value1 } What is the best way to compare the two objects above and determine if they are equal? ...