HTML and CSS Reference
In-Depth Information
When you start dragging, all you're doing is dragging. When you drop the ball, the motion code resumes
where it left off. The main problem now is that the velocity also resumes where it left off, which sometimes
results in the ball flying off in some direction when you release it—very unnatural looking. You can easily
fix that by setting vx and vy to zero, either when you start dragging or when you stop, as long as it is done
before the motion code resumes. Let's put it in the mousedown event handler:
canvas.addEventListener('mousedown', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
isMouseDown = true;
vx = vy = 0;
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mousemove', onMouseMove, false);
}
}, false);
That takes care of the problem and leaves you with a fully functional drag-and-drop feature with integrated
velocity, acceleration, and bouncing. You can see the full code listing in document 05-drag-and-move-
2.html.
Just one issue remains. When you drop the ball, it falls straight down—no more x-axis motion. Although
this is the correct behavior, it's a bit boring. If you could throw the ball and have it fly off in whatever
direction you threw it, that would be some engaging interactivity.
Throwing
What does throwing mean with regard to animation? It means you click an object to start dragging it and
move it in a particular direction. When you release it, the object keeps moving in the direction you were
dragging it.
For the velocity, you must determine what velocity the object has while it is being dragged, and then set
the object's velocity to that value when it is dropped. In other words, if you were dragging a ball 10 pixels
per frame to the left, then when you release it, its velocity should be vx = -10 .
Setting the velocity should be no problem for you. Just assign new values to vx and vy , as shown in
Figure 7-1. Determining what those values are might seem a little tricky, but actually, calculating the
dragging velocity is almost exactly the opposite of applying velocity in your motion code. In applying
velocity, you add velocity to the object's old position to come up with the object's new position. This
formula is old + velocity = new . To determine the velocity of an object while it's being dragged, you
simply rearrange the equation to get velocity = new - old .
vy
vx
Figure 7-1. A ball dragged to a new position. The velocity is the distance from its last position to this new position.
 
Search WWH ::




Custom Search