HTML and CSS Reference
In-Depth Information
Springing in two dimensions
The previous spring moved our ball along the x axis, or left-right. If we want the ball to spring along the x
axis and y axis—left-right and top-bottom—we need a two-dimensional spring. Creating this is as easy as
adding a second target, velocity, and acceleration; as we see in the next example, 07-spring-3.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Spring 3</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,
friction = 0.95,
targetX = canvas.width / 2,
targetY = canvas.height / 2,
vx = 0,
vy = 0;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = targetX - ball.x,
dy = targetY - ball.y,
ax = dx * spring,
ay = dy * spring;
vx += ax;
vy += ay;
vx *= friction;
vy *= friction;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
};
</script>
</body>
</html>
Here, the only difference from the previous example is all the references to the y-axis. The problem is that
it still seems rather one-dimensional. Yes, the ball is now moving on the x and y axes, but it's just going in
 
Search WWH ::




Custom Search