The Open-Source Game Development Pipeline

Providing the means and education to create games using free/libre open-source tools.


Leave a comment

Tweening Animation Using Three.js and Tween.js

Howdy folks!

I’ve been dabbling in web animation and graphics over the past week and thought I’d share a little demo I cooked up with Three.js. It utilizes the Tween.js animation library in order to chain transforms together and create some cool looking motion.

For your convenience, I thought I’d paste my “main.js” file here, and provide a link to the project below. Check it out:

var container;
var camera, scene, renderer, stats;
var cube;

var userOpts = {
range: 40,
duration: 3500,
delay: 200,
};

function setupTween()
{
var update = function(){
cube.position.x = current.x;
};

var current = { x: -userOpts.range };

TWEEN.removeAll();

var easing = TWEEN.Easing.Elastic.InOut;

var tweenHead = new TWEEN.Tween(current)
.to({x: +userOpts.range}, userOpts.duration)
.delay(userOpts.delay)
.easing(easing)
.onUpdate(update);

var tweenBack = new TWEEN.Tween(current)
.to({x: -userOpts.range}, userOpts.duration)
.delay(userOpts.delay)
.easing(easing)
.onUpdate(update);

tweenHead.chain(tweenBack);
tweenBack.chain(tweenHead);

tweenHead.start();
}

function init()
{
setupTween();

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera(30, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.z = 100;

var box = new THREE.BoxGeometry(20, 20, 20);
var mat = new THREE.MeshNormalMaterial();
cube = new THREE.Mesh(box, mat);
cube.position.x = -userOpts.range;

scene.add(cube);

container = document.createElement("div");
document.body.appendChild(container);

renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);

stats = new Stats();
stats.domElement.style.position = "absolute";
stats.domElement.style.top = "0px";
container.appendChild(stats.domElement);
}

function render()
{
requestAnimationFrame(render);
stats.update();
TWEEN.update();
renderer.render(scene, camera);
}

init();
render();

This is based upon some older code from here, but updated with today’s conventions.

You can download the project at this link.

Happy coding! 🙂

Cheers!

Advertisements