HTML and CSS Reference

In-Depth Information

Moving on a Vector

Moving between two points is handy, but sometimes you don't have a point to move to, only

a point to start from. In cases like this, it can be very useful to create a
vector
as a means to

move your object.

A
vector
is a quantity in physics that has both magnitude and direction. For our purposes, the

magnitude will be the
speed
value of the moving object, and the direction will be an
angle

value that the object will move upon.

The good news is that moving on a vector is very similar to moving between two points. In

canvasApp()
, we first set our
speed
value (magnitude). This is the number of pixels the ob-

ject will move on every call to
drawScreen()
. We will set this to
5
. We will also set the start-

ing point (
p1
) for the object to
20
,
20
:

var

var
speed
=
5
;

var

var
p1
=
{
x
:
20
,
y
:
20
};

Now, we will set the
angle
value (direction) of movement for our object to
45
degrees. In

mathematics, a flat, straight line usually represents the 0 angle, which means a vector with an

angle of 45 degrees would be down and to the right on the canvas.

With our angle set, we now need to convert it to radians. Radians are a standard unit of angle

measurement, and most mathematical calculations require you to convert an angle into radi-

ans before you can use it.

So why not just use radians and forget degrees altogether? Because it is much easier to under-

stand movement in degrees when working with vectors and moving objects on a 2D surface.

While a circle has 360 degrees, it has just about 6 radians, which are calculated counterclock-

wise. This might make perfect sense to mathematicians, but to move objects on a computer

screen, angles are much easier. Therefore, we will work with angles, but we still need to con-

vert our 45-degree angle into radians. We do that with a standard formula:
radians = angle

* Math.PI/ 180
. And in the code:

var

var
angle
=
45
;

var

var
radians
=
angle
*
Math
.
PI
/
180
;

Before we can discuss how we calculate the movement of our object along our vector, we

need to review a couple trigonometric concepts. These are
cosine
and
sine
, and both relate to

the arc created by our
angle
(now converted to
radians
), if it was drawn outward from the

center of the circle.