HTML and CSS Reference
In-Depth Information
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball0 = new Ball(),
ball1 = new Ball(),
ball2 = new Ball(),
spring = 0.03,
friction = 0.9,
gravity = 2;
function move (ball, targetX, targetY) {
ball.vx += (targetX - ball.x) * spring;
ball.vy += (targetY - ball.y) * spring;
ball.vy += gravity;
ball.vx *= friction;
ball.vy *= friction;
ball.x += ball.vx;
ball.y += ball.vy;
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
move(ball0, mouse.x, mouse.y);
move(ball1, ball0.x, ball0.y);
move(ball2, ball1.x, ball1.y);
//draw spring
context.beginPath();
context.moveTo(mouse.x, mouse.y);
context.lineTo(ball0.x, ball0.y);
context.lineTo(ball1.x, ball1.y);
context.lineTo(ball2.x, ball2.y);
context.stroke();
//draw balls
ball0.draw(context);
ball1.draw(context);
ball2.draw(context);
}());
};
</script>
</body>
</html>
If you take another look at the Ball class, you'll see that each object instance gets its own vx and vy
properties, and these are initialized to 0. So, at the top of the script, you just need to create each ball.
Then in the drawFrame function, you perform all the springing and drawing. Rather than duplicating the
same code three times for each ball, we include a move function, which handles all of the motion code.
This takes a reference to a ball and an x and y target. You call the function for each ball, passing in the x
and y mouse position for the first ball, and the location of the first and second balls as targets for the
second and third.
Search WWH ::




Custom Search