SnippetTweenBEGINNERButton Animations

Create Button Animation

This tutorial demonstrates how to create button animations using TWEEN.


button-animation_result


Button animations can be created by adjusting the position of the button.
We will use TWEENโ€™s .yoyo() function.

Adding Button Body and Button Objects

Add two desired meshes, such as a box or cylinder.


button-animation_step-1 Adding Button Body and Button

Basic Setup for Button Body and Button

a. Set the names of the objects to RedbuttonBody and Redbutton, respectively.

button-animation_step-2-a Setting Object Names

b. Change the color of the objects to your desired color.

button-animation_step-2-b Setting Object Color

c. Adjust the size of the button body.

button-animation_step-2-c Adjusting Button Body Size

d. Place the button as a child of the button body.

button-animation_step-2-d Adding Button as Child of Button Body

e. Adjust the size of the button.

button-animation_step-2-e Adjusting Button Size

f. Check the end position of the button and set it as the starting position.

button-animation_step-2-f Checking Button End Position
button-animation_step-2-g Setting Starting Position for Button
๐Ÿ’ก

By adding the button as a child object, it will move together with the button body. You can easily create button animations through the buttonโ€™s relative coordinates.

Writing TWEEN Script for Button Animation

Add the object (client) script to the button object. Use TWEEN to change the position of the button.
Since we are using .yoyo(), the button animation duration will be double the duration in tween.to(object, duration).

const tween = new TWEEN.Tween(this.position);
// Adjust the button animation time, the default is 1000ms
tween.to({ y : 0.1 }, 100) // duration
tween.yoyo(true).repeat(1);

The default transition time for TWEEN is 1000 milliseconds, or 1 second.

Executing TWEEN When the Button is Clicked

Use .onClick() to trigger TWEEN when the button is clicked.

// ...
 
this.onClick(() => {
    if(tween.isPlaying()) return;
    tween.start();
});

This checks if the current TWEEN is running, allowing the button to be pressed again after the button animation finishes.