Game Development Reference
In-Depth Information
float dx = (moveToPoint.x - c.x);
float dy = (moveToPoint.y - c.y);
float theta = atan(dy/dx);
float dxf = cos(theta) * self.speed;
float dyf = sin(theta) * self.speed;
if (dx < 0){
dxf * = −1;
dyf * = −1;
}
c.x += dxf;
c.y += dyf;
if (abs(moveToPoint.x - c.x) < speed && abs(moveToPoint.y - c.y) < speed){
c.x = moveToPoint.x;
c.y = moveToPoint.y;
}
[self setCenter:c];
}
In Listing 5-5, we see the
updateLocation
task of the class
Viper01
. This task is responsible for
moving the spaceship one frame's worth of movement toward the point
moveToPoint
. Because the
class
Viper01
extends
UIImageView
, we can move it by simply setting the standard properties used
to specify its location relative to its parent. We could use the
frame
property, but there is a property
called
center
that is a shorthand way of manipulating a
UIView
's frame.
We start calculating the spaceship's new
center
location by first getting a copy of its current
center
and storing that in the variable
c
. Next, we calculate the difference between the current location
and the location we are moving to for both the X and Y axis, storing the values in
dx
and
dy
. After
looking up the formula in our high school geometry topics, we calculate the angle that describes
the direction we are moving, by dividing
dy
by
dx
and passing the result to the
atan
(arc tangent)
function, storing the result as
theta
.
We want to move the spaceship speed a number of points in the direction of theta. To calculate what
that means in terms X and Y points, we have to do a little geometry. To calculate the number of
X points we will be moving, we take the cosine of
theta
and multiply it by
speed
, storing the value in
dxf
. Similarly, to calculate the number of Y points we have to move in this
frame
, we take the sine of
theta
and multiple by
speed
, storing the result in
dyf
. To finalize these values, we check to see if
dx
is
negative; if it is, we switch the signs of
dxf
and
dyf
.
Once
dxf
and
dyf
are calculated, we add those values to the
x
and
y
parts of the variable
c
. The last
thing we are going to do is set the
center
property with the new value stored in
c
. However, if we
are less than
speed
points from the
moveToPoint
, we will overshoot it. We don't want to overshoot
the point because, come next frame, we will overshoot again in the opposite direction, causing
the spaceship to jitter on the screen. To fix this, we simply set the
X
and
Y
values to be identical to
moveToPoint
's
X
and
Y
values if we are close to it. Figure
5-5
shows some of the geometry involved.