How can I defer Tween.js animation in three.js until a button is specifically clicked?

I am trying to implement a tween animation for my camera in three.js that should only start when a specific object is clicked. This object can be within the scene or it could be a simple HTML button. The code snippet below demonstrates how the camera animation currently functions:

            // initial position of camera
            var camposition = { x : 0, y: 0, z:3100 };
            // target position that camera tweens to
            var camtarget = { x : 0, y: 0, z:8500 };
            var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

            tweencam.onUpdate(function(){
                camera.position.x = camposition.x;
                camera.position.y = camposition.y;
                camera.position.z = camposition.z;
            });

            // delay tween animation by three seconds
            tweencam.delay(3000);

            tweencam.easing(TWEEN.Easing.Exponential.InOut);

            tweencam.start();

Instead of relying on a fixed time delay of three seconds before starting the animation, I am seeking a way to trigger the animation when the mouse1 button is clicked. I am unsure of how to achieve this functionality and if there are better alternatives available?

Answer №1

To initiate the tween animation when a button is clicked, simply enclose the beginning of the tween in a function and invoke this function on button click:

function startTweenAnimation() {
  tweencam.start();
}

<button onclick="startTweenAnimation()">Start Animation</button>

The complete code will appear like this:

// initial camera position
var camposition = {
  x: 0,
  y: 0,
  z: 3100
};
// target position for camera to animate towards
var camtarget = {
  x: 0,
  y: 0,
  z: 8500
};
var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

tweencam.onUpdate(function() {
  camera.position.x = camposition.x;
  camera.position.y = camposition.y;
  camera.position.z = camposition.z;
});

tweencam.easing(TWEEN.Easing.Exponential.InOut);

function startTweenAnimation() {
  tweencam.start();
}
<button onclick="startTweenAnimation()">Start Animation</button>

I trust this clarifies any confusion! :)

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

How to utilize hbs variable in an external JavaScript file

Currently, I am utilizing hbs (express handlebars) to display a page. I am interested in retrieving some variables from chat.hbs and accessing them in an external file named chat.js on the client side. Server Side res.render('chat', {chatr ...

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

Mui CardContent not displaying transparent background color properly

I recently completed a course that used MUI v4, and I'm now facing challenges with transitioning to v5. Despite my best efforts, I am struggling to replicate all the styles and find myself stuck. This issue relates to my FeaturedMovie.jsx component i ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

Unforeseen outcomes when setting background colors with Anime.js

I've recently started experimenting with Anime.js. I have a piece of code that I'm using to animate a div element with an id of a. anime({ targets: "#a", translateX: 250, color: "#fff", backgroundColor: "hsl(200, 50%, 50%)", ...

Caution: A duplicate key was found in ReactJS when attempting to flatten children

Currently, I am utilizing Tabs from Material UI to showcase a List component that is filtered by the tab. Take a look at the code snippet below from my Container Component: <Tabs className="DrawerTabs" ...

Transmit information from a bean to JavaScript using JSON in JavaServer Faces

I need help transferring my arraylist from a managedBean to JavaScript code. The bean code is shown below: public void getDataAsJson(){ String [] dizi={"Tokyo","Jakarta","New York","Seoul", "Manila","Mumbai","Sao Paulo","Mexico City", ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div: <div ng-controller = "myTest"> <div ng-repeat="name in names"> <h4>{{name.name}}</h4> <button ng-class="{'active ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...

What is the best way to create a function that will return a Promise within an Express Route?

I am working with a business level database module named "db_location" that utilizes the node-fetch module to retrieve data from a remote server through REST API. **db_location.js** DB LOGIC const p_conf = require('../parse_config'); const db_ ...

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

A different approach to making ajax requests

I'm currently conducting some experiments involving AJAX calls using pure JavaScript, without relying on JQuery. I am curious if it's possible to populate a DIV element in the following way: <script type="text/javascript"> function call_t ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...