HTML and CSS Reference
In-Depth Information
ball.vx *= friction;
ball.vy *= friction;
ball.x += ball.vx;
ball.y += ball.vy;
context.beginPath();
handles.forEach(drawHandle);
ball.draw(context);
}());
};
</script>
</body>
</html>
At the top of the script, we create a ball and three handles, randomly positioning the handles and setting
up their drag-and-drop behavior.
The drawFrame function loops through each handle, springing the ball toward it by calling the
applyHandle function. It then applies the ball's new velocity to its position, and loops through the handles
again, drawing a line from the ball to each handle. Then, finally, we draw the ball.
The mousedown event listener iterates over each handle, and if it finds one that contains the current
position of our mouse cursor, it sets that handle to movingHandle . In the mouseup event hander, if a
handle has been dragged, then it is stopped.
You can easily change the number of handles to use by changing the numHandles variable.
Figure 8-4. Multiple springs
Offsetting the target
If you took a real spring—an actual coil of bouncy metal—and attached one end of it to something solid
and the other end to a ball or some other object, what would be the target? Would the target be the point
where the spring is attached? No, not really. The ball would never be able to reach that point, because the
spring itself would be in the way. Furthermore, once the spring had contracted to its normal length, it
wouldn't be applying any more force on the ball. So, the target would actually be the position of the loose
end of the spring when it's not stretched. But that point could vary as the spring pivots around the fixed
point.
 
Search WWH ::




Custom Search