Smoothly animate the position of a THREE.JS Mesh

Can you help me with a question regarding three.js and x position translation of an imported .obj mesh?

I'm new to three.js and looking for guidance on how to solve this issue.

Basically, I have a mesh at (0,-200,0) and I want to smoothly move it to (50,-200,0) using a button to toggle back and forth between the two positions.

objLoader = new THREE.OBJLoader();
 objLoader.load('models/map_real.obj', function (obj) {

      var blackMat = new THREE.MeshStandardMaterial({color:0xfaf9c9});
      obj.traverse(function (child) {

         if (child instanceof THREE.Mesh) {
             child.material = blackMat;
         }

     });
     obj.castShadow = true;
     obj.receiveShadow = true;
     obj.position.set(0,-200,0)
     obj.rotation.y = getDeg(-20);
     scene.add(obj);
     objWrap = obj;

 });

In my main.js, I have an init() function that includes all the necessary functions like camera(), animate(), render(), etc. From the variable objWrap.position.x, I can see the correct position being logged.

I tried capturing the click event (as shown in the code snippet below) on my #test button and incrementing the position by 0.5. However, since it's not in the animate loop, it doesn't keep adding 0.5.

$('#test').click(function(){
    if (objWrap.position.x <= 50) {
    objWrap.position += 0.5}
});

What I want is a button that triggers a smooth animation from objWrap.position.x = 0 to objWrap.position.x = 50

I hope that was clear. Feel free to ask if you need more information, I'll respond promptly. Your assistance is greatly appreciated!

Answer №1

This is just a demonstration of how you can achieve it using Tween.js:

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.setScalar(50);
camera.lookAt(scene.position);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

scene.add(new THREE.GridHelper(200, 100));

let box = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshBasicMaterial({
  color: "aqua"
}));
scene.add(box);

btnMove.addEventListener("click", onClick, false);

let forth = true;

function onClick() {

  new TWEEN.Tween(box.position)
    .to(box.position.clone().setX(forth ? 50 : 0), 1000)
    .onStart(function() {
      btnMove.disabled = true;
    })
    .onComplete(function() {
      btnMove.disabled = false;
      forth = !forth;
    })
    .start();

}

render();

function render() {
  requestAnimationFrame(render);
  TWEEN.update();
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>
<button id="btnMove" style="position:absolute;">Move</button>

Answer №2

If you're working with ReactJS, it's important to import TWEEN into your project.

To do so, use the following code snippet:

import {TWEEN} from "three/examples/jsm/libs/tween.module.min";

This will enable drag controller and tween animation functionalities.

const { gl, camera } = useThree();
const objects = [];   // objects.push(ref.current)

useEffect(() => {
    const controls = new DragControls( objects, camera, gl.domElement );

    controls.addEventListener( 'dragend', (e) => {
         new TWEEN.Tween(e.object.position)
             .to(new Vector3(x, y, z), 1000)
             .easing(TWEEN.Easing.Back.InOut)
             .start();
    });
})

To display the animation properly, utilize UseFrame as shown below:

useFrame(() => {
    TWEEN.update();
});

I hope this information proves helpful to someone out there.

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

Implementing Google AdWords Conversion Tracking code on a button click event using knockoutjs

I recently received the following code snippet from Google AdWords for tracking purposes. <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 973348620; var google_conversion_language = "en"; var ...

Flick user media cards left or right to uncover the following one

I am currently working on creating a widget that will display user media objects in a horizontal layout using ng-repeat. The goal is to allow users to swipe left or right to reveal the next media card, similar to the image shown below. In the example, you ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

Creating an ngFor loop with an ngIf condition for true and false bot conditions

I am attempting to troubleshoot an issue where if my condition is true, return true. If my condition is false, return false. However, currently, if only one condition is true, all conditions are being applied as true. Please help me resolve this problem. ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Tips for transforming user inputs in HTML format into text within a prompt box

Is there a way to create a text prompt box for the user to input their name without risking the insertion of HTML elements into the page? I want to avoid any potential issues like inadvertently creating a new HTML element instead of displaying the intended ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

Developing a user authentication system with TowerJS

As a front-end designer/developer with limited MVC experience, I am looking to create a login form using TowerJS. Following the documentation, my app includes a model named "User": class App.User extends Tower.Model @field "email", type: "String" @fie ...

The 3D formula for calculating the distance between a point and a line

Can anyone provide me with a computer program or algorithm that calculates the distance between a point and a line in a three-dimensional space? The program can be written in JavaScript or any other programming language. In this scenario, P represents th ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

storage location for data in JSON format

When using content type : "application/x-www-form-urlencoded", the result is stored in Request.Form in Asp MVC. However, for "application/json", the storage location cannot be found. Below is the code that is being used: AJAX part // reading form da ...

Issue: 'The server cannot be started because the path is not defined' error message appears

Hey everyone, I'm currently working on implementing a forgot/reset password feature for my React Native app using this tutorial. However, when attempting to start the server, I encountered an error related to the 'path'. ReferenceError: pat ...

How can I properly parse a JSON file in Node.js?

Utilizing node.js, I have created a webpage (index.html) for visualizing a network graph using the vis.js library. To draw a network graph with this library, it is necessary to provide json arrays for both nodes and edges (see example). // array of nodes ...

ReCaptcha: connecting to the TextBox's OnKeyDown event using script

I've been figuring out how to integrate ReCaptcha, ASP.NET, and Gaia Ajax. It was a bit of a challenge to use the ReCaptcha AJAX APIs with Gaia to fetch the data from the recaptcha_response_field text box in an AJAX postback through a patch. This was ...

What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me. Why do we use <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not simply use <style href="min.css"></style>? Wh ...

Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to ...

Can a JavaScript function be used with images to operate across multiple elements?

How can I make a function work on multiple elements? let image = document.getElementById("opacityLink"); image.onmouseover = function() { image.style = "opacity:0.9"; }; image.onmouseout = function() { image.style = "opacity:1"; }; <div class=" ...

Retrieve values from a multi-level nested object by using square bracket notation for each level

I am in need of a config object to display nested data. Check out the demo code for reference In the code, accessing "customer.something" is essential. There can be multiple levels of nesting, which the grid handles with field='customer.som ...

Revitalize Your Preact SSR with Live Reload and Rebuilding

I'm currently exploring the option of implementing automatic browser refreshing in my preact ssr build development environment. package.json "scripts": { "test": "echo \"Error: no test specified\" &am ...

Dynamic manipulation of lighting effects in three.js during runtime

Is it possible to dynamically add and remove various light types in three.js during runtime? I have checkboxes that correspond to different types of lights, and I would like to add a specific light type to the scene when its checkbox is checked, and remov ...