HTML and CSS Reference
In-Depth Information
if (ball.x === targetX && ball.y === targetY) {
//code to stop the easing
}
But it winds up being a little more tricky. I touched on this problem in earlier chapters when we applied
friction, but we'll examine it in a little more detail here.
The type of easing we are discussing involves something from Zeno's Paradoxes. Zeno of Elea was a
Greek philosopher who devised a set of problems to show that, contrary to what our senses tell us, there is
no change, and motion is an illusion. To demonstrate this, Zeno explained motion as follows: In order for
something to move from point A to point B, it first must move to a point halfway between the two. Then it
needs to travel from that point to a point halfway between there and point B. And then halfway again.
Since you always need to move halfway to the target, you can never actually reach the target, since it is an
infinite amount of steps away.
It's a paradox because it sounds logical, but yet, our own experiences tell us that we move from point A to
point B every day. Let's take a look at it where the infinite breaks down in JavaScript. On the x axis, an
object is at position 0. Say you want to move it to 100 on the x axis. Make the easing variable 0.5, so it
always moves half the distance to the target. It progresses like this:
Starting at 0, after frame 1, it will be at 50.
Frame 2 will bring it to 75.
Now the distance is 25. Half of that is 12.5, so the new position will be 87.5.
Following the sequence, the position will be 93.75, 96.875, 98.4375, and so on. After 20 frames, it
will be 99.999809265.
As you can see, it gets closer and closer but never actually reaches the target—theoretically. However,
things are a bit different when you examine what the code does. Visually, it comes down to the question:
“How small can you slice a pixel?” And that answer is not specified in the HTML5 Canvas specification,
rather, it's defined by the browser implementation. Vendors could implement a high-resolution canvas with
a precision to many decimal places, but average viewer would have a very difficult time discerning a pixel
difference at 10 steps, meaning within 0.1.
In this example, the closest we can get the position to 100 after 20 steps is 99.99990463256836.
var position = 0,
target = 100;
for (var i = 0; i < 20; i++) {
console.log(i + ": " + position);
position += (target - position) * 0.5;
}
This loops through 20 times, moving the position half the distance to the target ; it's just basic easing
code. We're only interested in printing the positions, not actually seeing the motion. But, what you'll find is
that by the eleventh iteration, the position has reached 99.9, and when viewing this demonstration on
the canvas, that's as close as our ball will get.
Search WWH ::




Custom Search