Game Development Reference
In-Depth Information
self.clockwise = YES;
self.needsImageUpdated = YES;
} else {
self.rotation -= .1;
self.clockwise = NO;
self.needsImageUpdated = YES;
}
} else {//STATE_TRAVELING
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) < self.speed && abs(moveToPoint.y - c.y) < self.speed){
c.x = moveToPoint.x;
c.y = moveToPoint.y;
self.state = STATE_STOPPED;
self.needsImageUpdated = YES;
}
[self setCenter:c];
}
}
In Listing 5-25, we see that we now have a set of
if
statements that controls the ship's behavior
based on its state. If the ship is stopped, we check to see if it should stay stopped; if not, we switch
to the turning state and indicate that we need the image updated by setting
needsImageUpdated
to
YES
.
If the ship is in the turning state, calculate the angle we are turning toward based on
moveToPoint
and store the result in the variable
theta
. Because
atan
only returns a value between -
p
/2 and
p
/2,
we test to see if we should add
p
to get our
targetRotation
. Once we have our
targetRotation
value, we check to see how close the
targetRotation
is to the current rotation. If they are close, we
simply set
rotate
and to
targetRotation
and change
state
to
STATE_TRAVELING
. If we have not yet
reached our
targetRotation
value, we rotate the ship a little way toward our
targetRotation
. If the
ship is traveling, it moves toward the
moveToPoint
just as it did before.