Using tweens.js

Video Lecture

Using tweens.js Using tweens.js

Description

Tweenjs is a JavaScript tweening engine.

A tween (from in-between) is a concept that allows you to change the values of the properties of an object in a smooth way. We can decide how long it should take, and if there should be a delay, and what to do each time the tween is updated, whether it should repeat and other things.

Tween Easing Options

TWEEN.Easing.equation.direction

TWEEN.Easing.*equation*.*direction*

Start Code

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import express from "express"
import path from "path"
import http from "http"

const port: number = 3000

class App {
    private server: http.Server
    private port: number

    constructor(port: number) {
        this.port = port
        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))
        app.use('/build/three.module.js', express.static(path.join(__dirname, '../../node_modules/three/build/three.module.js')))
        app.use('/jsm/controls/OrbitControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/OrbitControls.js')))
        app.use('/jsm/loaders/GLTFLoader', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/loaders/GLTFLoader.js')))
        app.use('/jsm/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js')))
        app.use('/jsm/libs/tween.module.min', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/tween.module.min.js')))
        this.server = new http.Server(app);
    }

    public Start() {
        this.server.listen(this.port, () => {
            console.log( `Server listening on port ${this.port}.` )
        })
    }
}

new App(port).Start()

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader'
import Stats from '/jsm/libs/stats.module'
import { TWEEN } from '/jsm/libs/tween.module.min'

const scene: THREE.Scene = new THREE.Scene()
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 2

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.physicallyCorrectLights = true
renderer.shadowMap.enabled = true
renderer.outputEncoding = THREE.sRGBEncoding
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
//controls.addEventListener('change', render) //this line is unnecessary if you are re-rendering within the animation loop 

let sceneMeshes = []

const loader = new GLTFLoader()
loader.load(
    'models/monkey_textured.glb',
    function (gltf) {
        gltf.scene.traverse(function (child) {
            if ((<THREE.Mesh>child).isMesh) {
                let m = <THREE.Mesh>child
                m.receiveShadow = true
                m.castShadow = true;
                //(<THREE.MeshStandardMaterial>m.material).flatShading = true
                sceneMeshes.push(m)
            }
            if ((<THREE.Light>child).isLight) {
                let l = <THREE.Light>child
                l.castShadow = true
                l.shadow.bias = -.003
                l.shadow.mapSize.width = 2048
                l.shadow.mapSize.height = 2048
            }
        })
        scene.add(gltf.scene);
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded')
    },
    (error) => {
        console.log(error);
    }
);

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

const raycaster = new THREE.Raycaster();

renderer.domElement.addEventListener('dblclick', onDoubleClick, false);
function onDoubleClick(event) {
    const mouse = {
        x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    }
    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(sceneMeshes, false);

    if (intersects.length > 0) {

        const p = intersects[0].point
        //controls.target.set(p.x, p.y, p.z)

        // new TWEEN.Tween(controls.target)
        //     .to({
        //         x: p.x,
        //         y: p.y,
        //         z: p.z
        //     }, 500)
        //     //.delay (1000)
        //     .easing(TWEEN.Easing.Cubic.Out)
        //     //.onUpdate(() => render())
        //     .start();

    }
}

const stats = Stats()
document.body.appendChild(stats.dom)

const clock: THREE.Clock = new THREE.Clock()

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    TWEEN.update();

    render()

    stats.update()
};

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

./src/typings/tween.js/index.d.ts

Create a new folder called ./src/typings/tween.js/ and add the TypeScript definition file for tween.js and name it index.d.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
export class tween {
    Tween: typeof Tween
    update(time?: number): boolean
    getAll(): Tween[];
    removeAll(): void;
    add(tween: Tween): void;
    remove(tween: Tween): void;
    Easing: {
        Linear: {
            None: (amount: number) => number;
        };
        Quadratic: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Cubic: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Quartic: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Quintic: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Sinusoidal: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Exponential: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Circular: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Elastic: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Back: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
        Bounce: {
            In: (amount: number) => number;
            Out: (amount: number) => number;
            InOut: (amount: number) => number;
        };
    };
}
declare type EasingFunction = (amount: number) => number;
declare class Tween {
    constructor(object: any);
    isPlaying(): boolean;
    isPaused(): boolean;
    to(properties: {}, duration?: number): this;
    duration(value: number): this;
    start(time?: number | string): this;
    stop(): this;
    end(): this;
    pause(time: number): this;
    resume(time: number): this;   
    delay(amount: number): this;
    repeat(times: number): this;
    repeatDelay(amount: number): this;
    onStart(callback: (object: any) => void): this;
    onUpdate(callback: (object: any, elapsed: number) => void): this;
    onRepeat(callback: (object: any) => void): this;
    onComplete(callback: (object: any) => void): this;
    onStop(callback: (object: any) => void): this;
    easing(easing: EasingFunction): this;
}

declare const TWEEN: tween

./src/client/tsconfig.json

Update the compiler options paths to point to the new tween.js typescript definition file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{
    "compilerOptions": {
        "target": "ES6",
        "module": "ES6",
        "outDir": "../../dist/client",
        "baseUrl": ".",
        "paths": {
            "/build/three.module.js": ["../../node_modules/three/src/Three"],
            "/jsm/*": ["../../node_modules/three/examples/jsm/*"],
            "/jsm/libs/dat.gui.module": ["../typings/dat.gui"],
            "/jsm/libs/tween.module.min": ["../typings/tween.js"]
        },
        "moduleResolution": "node"
    },
    "include": [
        "**/*.ts"
    ]
}

Final Script

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader'
import Stats from '/jsm/libs/stats.module'
import { TWEEN } from '/jsm/libs/tween.module.min'

const scene: THREE.Scene = new THREE.Scene()
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 2

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()
renderer.physicallyCorrectLights = true
renderer.shadowMap.enabled = true
renderer.outputEncoding = THREE.sRGBEncoding
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
//controls.addEventListener('change', render) //this line is unnecessary if you are re-rendering within the animation loop 

let sceneMeshes = []

const loader = new GLTFLoader()
loader.load(
    'models/monkey_textured.glb',
    function (gltf) {
        gltf.scene.traverse(function (child) {
            if ((<THREE.Mesh>child).isMesh) {
                let m = <THREE.Mesh>child
                m.receiveShadow = true
                m.castShadow = true;
                //(<THREE.MeshStandardMaterial>m.material).flatShading = true
                sceneMeshes.push(m)
            }
            if ((<THREE.Light>child).isLight) {
                let l = <THREE.Light>child
                l.castShadow = true
                l.shadow.bias = -.003
                l.shadow.mapSize.width = 2048
                l.shadow.mapSize.height = 2048
            }
        })
        scene.add(gltf.scene);
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded')
    },
    (error) => {
        console.log(error);
    }
);

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

const raycaster = new THREE.Raycaster();

renderer.domElement.addEventListener('dblclick', onDoubleClick, false);
function onDoubleClick(event) {
    const mouse = {
        x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    }
    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(sceneMeshes, false);

    if (intersects.length > 0) {

        const p = intersects[0].point
        //controls.target.set(p.x, p.y, p.z)

        // new TWEEN.Tween(controls.target)
        //     .to({
        //         x: p.x,
        //         y: p.y,
        //         z: p.z
        //     }, 500)
        //     //.delay (1000)
        //     .easing(TWEEN.Easing.Bounce.Out)
        //     //.onUpdate(() => render())
        //     .start();

        new TWEEN.Tween(sceneMeshes[1].position)
            .to({
                x: p.x,
                //y: p.y + 1,
                z: p.z
            }, 500)
            .start()

        new TWEEN.Tween(sceneMeshes[1].position)
            .to({
                //x: p.x,
                y: p.y + 3,
                //z: p.z
            }, 250)
            //.delay (1000)
            .easing(TWEEN.Easing.Cubic.Out)
            //.onUpdate(() => render())
            .start()
            .onComplete(() => {
                new TWEEN.Tween(sceneMeshes[1].position)
                    .to({
                        //x: p.x,
                        y: p.y + 1,
                        //z: p.z
                    }, 250)
                    //.delay(250)
                    .easing(TWEEN.Easing.Bounce.Out)
                    //.onUpdate(() => render())
                    .start()
            })

    }
}

const stats = Stats()
document.body.appendChild(stats.dom)

const clock: THREE.Clock = new THREE.Clock()

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    TWEEN.update();

    render()

    stats.update()
};

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

tween.js GitHub