Game Development Reference
In-Depth Information
Listing 7-5. FollowActor.m
#import "FollowActor.h"
#import "GameController.h"
@implementation FollowActor
@synthesize actorToFollow;
@synthesize xOffset;
@synthesize yOffset;
+(id)followActor:(Actor*)anActorToFollow{
FollowActor* follow = [FollowActor new];
[follow setActorToFollow:anActorToFollow];
return follow;
}
-(void)applyToActor:(Actor*)anActor In:(GameController*)gameController{
if (![actorToFollow removed]){
CGPoint c = [actorToFollow center];
c.x += xOffset;
c.y += yOffset;
[anActor setCenter: c];
} else {
[gameController removeActor:anActor];
}
}
@end
In Listing 7-5, we see the entire implementation of the class
FollowActor
. It is constructed with the
task
followActor:
, which takes the actor to follow as an argument. The task
applyToActor:In:
is called for every step of the game and is responsible for repositioning the actor this
behavior
is
associated with. To do this, we simply set the property
center
of
anActor
to the property
center
of
the
Actor
we are following, adjusting by
xOffest
and
yOffset
. Looking at Listing 7-4, we see that the
HealthBar
is configured to follow the
saucer
at an
xOffset
equal to the
radius
of
saucer
. This keeps
the
HealthBar
centered below
saucer
. Now let's explore the
Bullet
class.
The Bullet Class
We have seen how the
Saucer
and the
HealthBar
classes work together. We now want to look at the
Bullet
class and understand why it behaves the way it does. Listing 7-6 shows
Bullet
's constructor.
Listing 7-6. Bullet.m (bulletAt:WithDirection:)
+(id)bulletAt:(CGPoint)aCenter WithDirection:(float)aDirection{
VectorRepresentation* rep = [VectorRepresentation vectorRepresentation];
Bullet* bullet = [[Bullet alloc] initAt:aCenter WithRadius:4 AndRepresentation:rep];
[rep setDelegate:bullet];