Game Development Reference
In-Depth Information
-(void)setDirection:(float)aDirection{
direction = aDirection;
deltaX = cosf(direction)*speed;
deltaY = sinf(direction)*speed;
}
-(void)applyToActor:(Actor*)anActor In:(GameController*)gameController{
CGPoint center = anActor.center;
center.x += deltaX;
center.y += deltaY;
if (wrap){
CGSize gameSize = [gameController gameAreaSize];
float radius = [anActor radius];
if (center.x < -radius && deltaX < 0){
center.x = gameSize.width + radius;
} else if (center.x > gameSize.width + radius && deltaX > 0){
center.x = -radius;
}
if (center.y < -radius && deltaY < 0){
center.y = gameSize.height + radius;
} else if (center.y > gameSize.height + radius && deltaY > 0){
center.y = -radius;
}
}
[anActor setCenter:center];
}
We calculate the values deltaX and deltaY each time the speed or direction values are set. The
task applyToActor:In : is defined by the protocol Behavior and is called by a GameController to give
a Behavior a chance to modify an actor. In the implementation of applyToActor:In : for the class
LinearMotion , we start by getting the current center of the actor and increase the X and
Y components by deltaX and deltaY .
If wrap is true, we have to see whether the actor is outside the game area. This is a little more
complex than simply checking whether center is inside gameArea or not, because we have to take
into account the radius of the actor as well. We want an actor to appear as though it is traveling
offscreen instead of simply vanishing when it touches the edge of the screen. Also, we want to
move an actor only if it is moving away from the game area. Keeping these two things in mind, we
test whether the X value of center is less than radius and has a negative deltaX . This means the
actor is to the left of the game area and moving left, away from the game area. So we had better
move it to the right of the game area, so its leftward motion brings the actor back onto the right side
of the screen. We perform the opposite operation if the X value of center is greater than the width of
the game area and is moving to the right, moving the actor to the left side of the screen. These two
tests are repeated for the center's Y value.
The implementation of LinearMotion is pretty simple, only slightly complicated by the notion of
wrapping. Next, we will explore the class ExpireAfterTime , which is used to remove actors from the
scene after a given time.
 
Search WWH ::




Custom Search