HTML and CSS Reference
In-Depth Information
vx
vy
Total
velocity
Figure 5-7. This represents velocities as vectors, and it looks like the same right-angle triangle pictured in Figure 5-5!
Take that as a sign that you are doing something right.
A mouse follower
Let's use the velocity concepts to expand on an earlier concept. In Chapter 3, you built an example with an
arrow that always pointed to the mouse. That example used Math.atan2 to compute the angle between
the mouse and the arrow, and then rotated the arrow so it lined up with that angle.
With what you just learned, you can now throw some speed into the mix and get a velocity based on the
current angle. We then move the arrow based on the mouse position so it follows our cursor. This example
uses the same Arrow class, rather than the ball. So find that file, or rewrite the class and put it in the same
directory as the next document, 04-follow-mouse.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Follow Mouse</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="arrow.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
arrow = new Arrow(),
speed = 3;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
 
Search WWH ::




Custom Search