## Tuesday, March 26, 2013

### Just the Abstractions

‹prev | My Chain | next›

I can simulate jumping in Three.js with `Math.sin()`. I can also simulate jumping with a less trigonometrically challenged (but more opaque) JavaScript function. I lean toward `Math.sin()` because it looks better and is easier to explain conceptually. Sines and cosines might give some flashbacks to painful high school math, but kids do not need that level of explanation in 3D Game Programming for Kids—just the abstractions.

It occurs to me that the easiest way to choose might be to implement the other proposed enhancement to my avatar world: shaking.

Specifically, I would like the tree to randomly shake. I have a list of trees already:
``````  var trees = [];
trees.push(makeTreeAt( 500,  0));
trees.push(makeTreeAt(-500,  0));
trees.push(makeTreeAt( 750, -1000));
trees.push(makeTreeAt(-750, -1000));``````
I can then randomly pick a tree, and shake it with a sine Tween:
``````  function shakeTree() {
var active = Math.floor(Math.random() * trees.length);

new TWEEN
.Tween({jump: 0})
.to({jump: 32*Math.PI}, 8*1000)
.onUpdate(function () {
trees[active].position.x = 100* Math.sin(this.jump);
})
.start();

setTimeout(shakeTree, 12*1000);
}
shakeTree();``````
And that works:

So problem solved and sine and cosines it is. As I found last night one back-and-forth without trigonometry is not-great-but-not-horrible. But There is no way I can explain multiple repetitions to kids. Unless...

Unless Tween.js supports a `repeat()` method:
``````  function shakeTree() {
var active = Math.floor(Math.random() * trees.length);

new TWEEN
.Tween({jump: -1})
.to({jump: 1}, 1000)
.repeat(10)
.onUpdate(function () {
trees[active].position.x = 100 * (1 - Math.abs(this.jump));
})
.start();

setTimeout(shakeTree, 12*1000);
}
shakeTree();``````
Of course, Tween.js does support this method (though I have to upgrade). So I am no better off—at least not at having a decision made for me.

While digging through Tween.js, I run across one other method that I hoped would exist: `removeAll()`. This stops all Tweens when, for instance, the player jumps:
``````  function jump() {
TWEEN.removeAll();
new TWEEN
.Tween({jump: 0})
.to({jump: Math.PI}, 500)
.onUpdate(function () {
marker.position.y = 200* Math.sin(this.jump);
})
.start();
}``````
Once all current Tweens are removed, I am free to start up a new one—jumping in this case. I am definitely going to need that.

I do think that I will stick with sines and cosines, but is to good to know about Tween's `repeat()` even if I do not use it here, I have the feeling that it will come in handy somewhere else.

Day #702