HTML and CSS Reference
In-Depth Information
Before you write any code, we'll simulate it with some sample numbers. Let's say the x position is 0, vx is
0, the target x is 100, and the spring variable is 0.1. Here is how it might progress:
1.
Multiply distance (100) by spring , and you get 10. Add that to vx , which then becomes 10. Add
velocity to position, making the x position 10.
2.
Next round, distance (100 - 10) is 90. Acceleration is 90 times 0.1, or 9 this time. This gets added
to vx , which becomes 19. The x position becomes 29.
Next round, distance is 71, acceleration is 7.1, which added to vx makes it 26.1. The x position
becomes 55.1
3.
Next round, distance is 44.9, acceleration is 4.49, and vx becomes 30.59. The x position is then
85.69.
4.
The acceleration on each frame becomes less and less as the object approaches its target, but the
velocity continues to build. It's not building as rapidly as it was on previous frames, but it's still moving
faster and faster.
After a couple more rounds, the object goes right past the target to an x position of around 117. The
distance is now 100 - 117, which is -17. A fraction of this gets added to the velocity, slowing the object
down a bit.
Now that you understand how springing works, let's make a real example. As usual, make sure the Ball
class is available to your document, and use the following file ( 05-spring-1.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Spring 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
spring = 0.03,
targetX = canvas.width / 2,
vx = 0;
ball.y = canvas.height / 2;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = targetX - ball.x,
Search WWH ::




Custom Search