HTML and CSS Reference
In-Depth Information
Angular acceleration
As mentioned, acceleration has a value—the force—and a direction, just like velocity. And like velocity, if
you start with those two factors, you need to break them down into the component x and y forces. Now, if
you are paying attention, you know that the way to do that is by using
Math.cos
and
Math.sin
. Here's
how that looks:
var force = 10,
angle = 45, //degrees. Need to convert!
ax = Math.cos(angle * Math.PI / 180) * force,
ay = Math.sin(angle * Math.PI / 180) * force;
Now that you have acceleration for each axis, you can update the velocity on each axis, and from that,
update the object's position.
Let's resurrect the mouse follower example from earlier in the chapter and make it work with acceleration
instead of just plain velocity. Because that example used the
Arrow
class, find the
arrow.js
file to include
in this exercise. Remember that in the earlier incarnation, you took the angle from the arrow to the mouse
and used that to determine
vx
and
vy
. This time, you use the same calculations, but employ them to
determine
ax
and
ay
instead. Then you add the acceleration values to the velocity values and the velocity
values to the
x
and
y
properties. Here's the code
(10-follow-mouse-2.html)
:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Follow Mouse 2</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(),
vx = 0,
vy = 0,
force = 0.05;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = mouse.x - arrow.x,
dy = mouse.y - arrow.y,
angle = Math.atan2(dy, dx), //radians
ax = Math.cos(angle) * force,
ay = Math.sin(angle) * force;