Explanation
The variables you set are speed (in any direction), acceleration,
friction, maxspeed, and rspeed (rotation speed of how fast
the car will turn).
First up in the onEnterFrame function you check if the
up key is down. This time, you only use one speed and determine
the x and y speeds by using this and the car's rotation.
Like you have done before, the speed will have acceleration
added or taken from it depending what key is down, and
if none of them are down, the speed will be multiplied
by friction (0.9) which takes it closer to 0 each frame.
Flash uses what is called radians for a lot of actionscript
calculations, if you don't know what they are, don't worry
- all you need to know is that it's another form of representing
angles, like degrees. The _rotation property of a MC is
given in degrees, however, so you need to convert this
to radians by multiplying it by pi (π) divided by 180.
To go from radians > degrees, multiply by 180 divided
by π. You assign this value to a variable rad, which
will be used in the next few lines.
You then check if the speed goes over the maxspeed or
under the negative maxspeed. If it does, assign it to maxspeed.
Then you control the rotation of the car depending on
what key is down. If the left key is down, the rotation
will have rspeed subtracted from it or it will rotate anticlockwise
rspeed degrees. If the right key is down, the rotation
will rotate clockwise rspeed degrees.
Here comes the hardest part to understand, especially
if you don't have an understanding of basic trigonometry
(that sine and cosine stuff). If you don't, look here -
http://en.wikipedia.org/wiki/Trigonometric_function. Imagine
the car's movement over 2 frames as a triangle:
You know the speed and the rotation, and you can use trigonometry
to find out the xspeed and yspeed.
Something you should know is that a MC's rotation is measured
from a line pointing straight up going around clockwise
to the rotation line, so if it was the hour hand on a clock,
at 12 o'clock it would have a rotation of 0, at 3, rotation
is 90 and so on.
The triangle I drew showed xspeed and yspeed positive
on a regular cartesian plane (note this for later), so
you could see the rotation of the car. Using trigonometry,
the sine of the angle is the xspeed divided by the speed
(which is the hypoteneuse). So,
xspeed = sine(rotation) x speed
and in actionscript:
xspeed = Math.sin(rad)*speed
where you use radians because that's how Actionscript calculates
sine functions.
Also, the cosine of the angle is the yspeed divided by
the speed:
yspeed = Math.cos(rad)*speed
However, the Flash stage is not your regular cartesian
plane. Remember (or not) that the y values on the Flash
stage are opposite from the regular (ie the y values are
more positive as you go down). Because of this, you need
to make this negative by multiplying by negative speed
instead of just speed.
Then you do the usual by adding x and y speeds onto the
x and y positions of the car. |