Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRotationMatrix to use it as the end rotation for my tween animation.

UPDATE:

Here is my current progress:

// function for rotating dice
function moveCube() {

    // resetting parent object rotation
    pivot.rotation.set( 0, 0, 0 );
    pivot.updateMatrixWorld();
    // attaching dice to pivot object
    THREE.SceneUtils.attach( dice, scene, pivot );

    // setting variables for rotation direction
    var rotateZ = -1;
    var rotateX = -1;
    if (targetRotationX < 0) {
        rotateZ = 1;
    } else if (targetRotationY < 0) {
        rotateX = 1;
    }

    // determining which drag direction was higher
    if (Math.abs(targetRotationX) > Math.abs(targetRotationY)) {
            // rotating
            var newPosRotate = {z: rotateZ * (Math.PI / 2)};
            new TWEEN.Tween(pivot.rotation)
                .to(newPosRotate, 2000)
                .easing(TWEEN.Easing.Sinusoidal.InOut)
                .start();
            //rotateAroundWorldAxis(dice, new THREE.Vector3(0, 0, rotateZ), Math.PI / 2);
    } else {
            // rotating
            var newPosRotate = {x: -rotateX * (Math.PI / 2)};
            new TWEEN.Tween(pivot.rotation)
                .to(newPosRotate, 2000)
                .easing(TWEEN.Easing.Sinusoidal.InOut)
                .start();
            //rotateAroundWorldAxis(dice, new THREE.Vector3(-rotateX, 0, 0), Math.PI / 2);
    }

    // detaching dice from parent object
    THREE.SceneUtils.detach( dice, pivot, scene );
}

Thanks to WestLangley, I believe I am getting closer to a solution that is simple and effective. By initializing the pivot object with the same position as the dice, the rotation will still be centered around the dice's center.

var loader = new THREE.JSONLoader();
loader.load(
    'models/dice.json',
    function ( geometry, materials ) {
        material = new THREE.MeshFaceMaterial( materials );
        dice = new THREE.Mesh( geometry, material );
        dice.scale.set(1.95, 1.95, 1.95);
        dice.position.set(2.88, 0.98, 0.96);
        scene.add( dice );

        pivot = new THREE.Object3D();
        pivot.rotation.set( 0, 0, 0 );
        pivot.position.set(dice.position.x, dice.position.y, dice.position.z);
        scene.add( pivot );
    }
);

The current solution I have implemented (shown in the above snippet) does not properly attach the dice to the pivot object as its parent. I may be missing something quite basic...

UPDATE END

Answer №1

It turned out that the solution to my problem was quite simple:

All I had to do was move the detachment of the child object (the dice) to the beginning of the function instead of having it at the end. Once I made this change, everything worked perfectly.

Below is the updated code snippet:

// Function for rotating dice
function moveCube() {
    // Detach dice from parent object first so attaching child object works correctly
    THREE.SceneUtils.detach( dice, pivot, scene );
    // Reset parent object rotation
    pivot.rotation.set( 0, 0, 0 );
    pivot.updateMatrixWorld();
    // Attach dice to pivot object
    THREE.SceneUtils.attach( dice, scene, pivot );

    // Set variables for rotation direction
    var rotateZ = -1;
    var rotateX = -1;
    if (targetRotationX < 0) {
        rotateZ = 1;
    } else if (targetRotationY < 0) {
        rotateX = 1;
    }

    // Check which drag direction was higher
    if (Math.abs(targetRotationX) > Math.abs(targetRotationY)) {
            // Rotation
            var newPosRotate = {z: rotateZ * (Math.PI / 2)};
            new TWEEN.Tween(pivot.rotation)
                .to(newPosRotate, 2000)
                .easing(TWEEN.Easing.Sinusoidal.InOut)
                .start();
    } else {
            // Rotation
            var newPosRotate = {x: -rotateX * (Math.PI / 2)};
            new TWEEN.Tween(pivot.rotation)
                .to(newPosRotate, 2000)
                .easing(TWEEN.Easing.Sinusoidal.InOut)
                .start();
    }
}

Thank you very much for your assistance!

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

What is the proper way to utilize the decodeURIComponent function?

router.get("/stocks/authed/:symbol", function (req, res, next) { req.db .from("stocks") .select("*") .modify(function(queryBuilder) { if (req.query.from && req.query.to) { queryBuilder.whereBetween('timestamp&apos ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

What is the best way to align a popup window with the top of the main window?

I have successfully created a simple lightbox feature where a popup window appears when a thumbnail is clicked. My question is, how can I use jQuery to detect the top position so that the popup div always appears around 200px from the top of the window? $ ...

After logging in successfully, the React app needs a hard refresh to update the

I'm encountering a debugging challenge and would appreciate any assistance from the community. I've been working on my first React app and successfully implemented a Login feature, but after a user logs in, they have to hard refresh their browser ...

Interpolating UV is not allowed: 'flat': Using a reserved word in an illegal manner

As a beginner, I recently learned that UV coordinates are not interpolated in WebGL, allowing for exact pixel values to be retrieved. However, when attempting to use the 'flat' keyword, I encountered an error. By adding 'flat' before t ...

Is it possible for my website to send an email without the need for a script to be executed?

Looking to include a contact page on my website, but struggling with limitations imposed due to hosting on a secure school server that restricts script execution. Wondering if there's a workaround that would allow for email sending on the client side ...

What is the best way to utilize RxJs with jQuery's ajax function?

Here is how I've set it up: Rx.Observable.fromPromise($.ajax({ url: url + postal_value + '&types=(regions)&location=51.509865,-0.118092&key=' + key, type: "GET", datatype: "json" })); However, the aj ...

Tips for relocating a popup window''s position

A situation has arisen in my application where a popup window is opened with the following code: function newPopup(url, windowName) { window.open(url,windowName,'height=768,width=1366,left=10,top=10,titlebar=no,toolbar=no,menubar=no,location=no,d ...

Implementing dynamic option selection in Vue using JavaScript and v-model

Is there a way to manage the chosen value in a v-modeled select tag using vue.js? I created a jsFiddle demonstration, but unfortunately, it is not functioning correctly. This leads to my inquiry: vm.$set('selected', '1') // does not wo ...

Using Angular to pass parameters to a function

When passing a parameter to the getActiveId function in the ng-click <span class="col ion-ios7-heart-outline center" ng- click="getActiveId({{activeSlide.selected}})"> The value turns to zero in the controller, but it is passed correctly after tes ...

What is the method for transferring form data to a different page?

Currently utilizing AngularJS version 1.5.6 and looking for guidance on properly passing form data using $location.path. Below is my code snippet for Page A: <form> ... <button type="submit" ng-click="submit(formData)"> ...

Breaking down React.js element

This Navigation component handles various functionalities related to user authentication and routing. import React from 'react'; import {Navbar, Nav, NavItem, Modal, Button, FormControl} from 'react-bootstrap'; import {BrowserRouter, L ...

Having trouble retrieving a JSON Element in JavaScript using the Object's property

I am having trouble retrieving a specific JSON element from the following JSON structure: { "ACTION": "AA", "MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01" } Even though I receive the data in JSON format, attempting to access data.ACTION or d ...

jQuery wrapAll issue

I have a repeating group of three divs in my code that I need to wrap together. Here's an example from my HTML: <div class="one" /> <div class="two" /> <div class="three" /> <div class="one" /> <div class="two" /> <d ...

Creating a URL using Form Fields with Javascript or jQuery - Reg

Creating a Custom URL with Form Fields using JavaScript or jQuery I am looking to generate an external link by incorporating a form with a dynamic variable as shown below: (Where 2500 can be customized based on user input) The final URL will be display ...

What steps should be taken in order to ensure the effectiveness of this keyword search

Currently, I am attempting to implement a keyword search feature for my meteor web app. Although the functionality is there, it's running quite slow. The way it works now is that when a user creates an article, they assign keywords to it. The keyS fun ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

Utilizing Backbone script for fetching data from an external JSON source

I am seeking assistance on how to utilize a Backbone script to display data from a JSON file. Here is the structure of the HTML Page: <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</tit ...