Tips for effectively utilizing Timelinemax and Tween for object animation

Hello Amazing Stackoverflow community,

I've been attempting to move my object in three.js to a specific point. I believe I need to utilize Tween.js for this task. However, in the tutorial I followed, they imported Tween Js but used 'timelinemax' which confused me a bit.

Below is my code snippet:


var scene = new THREE.Scene();

scene.background = new THREE.Color(0xf0f0f0);
var camera = new THREE.PerspectiveCamera(100, window.innerWidth/window.innerHeight, 0.1, 3000);
camera.position.x = 40;
camera.position.y = 20;
camera.position.z = 1500;

var renderer = new THREE.WebGLRenderer();
var render = function() {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var coord = [{"x":300,"y":10,"z":10},{"x":20,"y":30,"z":30},{"x":30,"y":0,"z":50},
            {"x":40,"y":20,"z":70},{"x":50,"y":100,"z":90},
            {"x":60,"y":30,"z":110},{"x":70,"y":150,"z":90}];

var sphr;
var geom;
var sphrinfo = [];

function drawsphere() {
    for (let i=0; i<coord.length; i++) {
        var mat = new THREE.MeshPhongMaterial({flatShading: true});
        geom = new THREE.SphereGeometry(60, 50, 50);
        sphr = new THREE.Mesh(geom, mat);

        sphr.position.set(coord[i].x, coord[i].y, coord[i].z)
        sphrinfo.push(sphr)

        sphr.tl = new TimelineMax()
        sphr.tl.to(sphr.position.set, .5, {x:100, y:204, z:300})

        scene.add(sphr);
        render();
    }
}

drawsphere();

function movesphere() {
    for (let i=0; i<coord.length; i++) {
        sphrinfo[i].z = 10;
    }
}

function animate() {
    
}

var light = new THREE.AmbientLight(0x404040);
scene.add(light);

var directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
scene.add(directionalLight);

I included TimelineMax to animate the spheres, but unfortunately, they do not move at all. Can someone assist me in resolving this issue?

My ultimate goal is to generate multiple spheres with specific x, y, z values and then have them drop to the plane where the z coordinate is zero, animating the process.

Thank you in advance.

Answer №1

Adolescents focus on properties, however, you are attempting to tween sphr.position.set which is a function.
You should simply tween the x, y and z values on sphr.position.

Displayed below is a demonstration, refer to the animateBox function.

var camera, scene, renderer, mesh, material;
init();
renderloop();
// Initiate animation of the box.
animateBox();

function init() {
    // Renderer.
    renderer = new THREE.WebGLRenderer();
    //renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    // Add renderer to page
    document.body.appendChild(renderer.domElement);

    // Create camera.
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 800;

    // Create scene.
    scene = new THREE.Scene();

    // Create material
    material = new THREE.MeshPhongMaterial();

    // Create cube and add to scene.
    var geometry = new THREE.BoxGeometry(200, 200, 200);
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    // Create ambient light and add to scene.
    var light = new THREE.AmbientLight(0x404040); // soft white light
    scene.add(light);

    // Create directional light and add to scene.
    var directionalLight = new THREE.DirectionalLight(0xffffff);
    directionalLight.position.set(1, 1, 1).normalize();
    scene.add(directionalLight);

    // Add listener for window resize.
    window.addEventListener('resize', onWindowResize, false);

}

function renderloop() {
    requestAnimationFrame(renderloop);
    renderer.render(scene, camera);
}

function animateBox() {
  
  // only incorporate tweens.
  //gsap.to(mesh.position, {x: Math.floor((Math.random() * 600) - 300), duration: 5, ease: "elastic"});
  //gsap.to(mesh.position, {y: Math.floor((Math.random() * 600) - 300), duration: 5, ease: "elastic"});
  //gsap.to(mesh.position, {z: Math.floor((Math.random() * 600) - 300), duration: 5, ease: "elastic"});
  
  // utilize a timeline (and call this function again upon completion).
  // This makes use of GSAP V3
  var timeline = gsap.timeline({onComplete: animateBox});

  // animate mesh.position.x,
  // a random number between -300 and 300,
  // for 2 seconds.
  timeline.to(
    mesh.position,
    {x: Math.floor((Math.random() * 600) - 300), duration: 2, ease: "elastic"},
    0
  );
  
  // animate mesh.position.y
  timeline.to(
    mesh.position,
    {y: Math.floor((Math.random() * 600) - 300), duration: 2, ease: "elastic"},
    0
  );

  // animate mesh.position.z
  timeline.to(
    mesh.position,
    {z: Math.floor((Math.random() * 600) - 300), duration: 2, ease: "elastic"},
    0
  );
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
    padding: 0;
    margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.5/gsap.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.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

Getting a value from a Child component to a Parent component in Nuxt.js - a step-by-step guide

I am facing a challenge in passing data from Child A component to Parent, and then from the Parent to Child B using props. In my project using nuxt.js, I have the following structure: layouts/default.vue The default template loads multiple components wh ...

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

Enhancing the default functionality of React.FC within Next.js

Currently, I am working on a tutorial in Nextjs that employs the code snippet below in JavaScript. However, I am planning to transition it to TypeScript. Since I am relatively new to TypeScript, I have attempted various solutions from different sources but ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Conditionally enable or disable button by comparing textbox values within a gridview using C# programming

Hey there! I'm currently diving into the world of JavaScript and C#. Feel free to correct me if you see any mistakes along the way. Check out my gridview code snippet below: <asp:GridView ID="GridView1" CssClass="table table-hover table-bordered" ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Navigating to a different intent within the DialogFlow Messenger fulfillment can be done by utilizing the 'agent.setFollowupEvent(targetIntentEventName)' method

I am currently exploring ways to initiate another DialogFlow Intent (using its event) from a webhook server built with node.js. This will occur after gathering the user's email address, verifying their registration status by sending a POST API request ...

Assigning values to props in a Vue component

I created a Vue component that is supposed to receive the "uploadedFile" prop, but it's not functioning properly. I am only getting the correct information in the $attrs: https://i.sstatic.net/crXmH.png Here is my component: Vue.component('t ...

Discover a way to retrieve the index of elements in Vue JS that are not within a v-for loop

I am interested in learning how to access the index of elements outside of a v-for loop <template> <div class="hero-text"> <h4>0{{ index + 1 }}/{{ homePageImageList.length }}</h4> </div> <VueSlickC ...

The problem with document.cookie: Functions properly on localhost but displays as empty when hosted on the web

I have been exploring various resources, but none seem to describe my unique situation. Currently, I am in the process of creating a website using ReactJS for the front-end and NodeJS with Express for the back-end. The production versions are accessible a ...

Employing the CSS not selector within JavaScript

I am facing an issue where my form darkens with the screen every time I click a button to show it, using JavaScript. If I were using CSS, I know I could use the :not selector, but I need guidance on how to achieve this in JS. Can anyone assist me? Below i ...

What is the best way to auto-fill input fields with data from a Json file

My goal is to automatically populate HTML form fields based on user selection. I have obtained code for related functions, such as fetching JSON data and creating dropdown lists, from a friend. Here is the link to that code: https://jsfiddle.net/r4zuy7tn/1 ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...

When multiple pages are open and one page remains idle, the user session will time out due to the timer implemented in JS/JQuery

I currently have a user activity monitoring system in place on my webpage. When a user is inactive (i.e. doesn't move the mouse) for 30 minutes, a warning is displayed informing the user that their session will expire soon. If the user does not intera ...

Is your form complete?

Is there a way to determine if all required fields in the current form are correctly filled in order to disable/enable navigation? Are there any specific properties or JQuery functions that can be used to check for form completion status? ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

Ways to assess the efficiency of the client browser using JavaScript

As I work on creating my website, I have come across an issue with lag when scrolling through a certain viewport that contains a canvas element. To address this problem, I am looking to analyze the browser's performance, specifically focusing on the f ...

Issue with MUI DataGridPro failing to sort the email field

I am facing an issue with the sorting functionality in the email field while creating a table using MUI DataGridPro. The sorting works fine for all other fields except for the email field. Adding some random text here to ensure my question is published. Pl ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

What is the best approach for creating a dynamic table in this situation?

I am struggling with creating a table from a variable that contains an array of arrays, which is parsed code from an excel file. I attempted to upload the file and build the table using the following approaches: tabela.forEach((elem, index) => { cons ...