Game Development Reference
In-Depth Information
@interface LinearMotion : NSObject <Behavior>{
float deltaX;
float deltaY;
}
@property (nonatomic) float speed;
@property (nonatomic) float direction;
@property (nonatomic) BOOL wrap;
+(id)linearMotionInDirection:(float)aDirection AtSpeed:(float)aSpeed;
+(id)linearMotionRandomDirectionAndSpeed;
@end
The class LinearMotion extends NSObject and conforms to the protocol Behavior, which was
imported from Actor.h . The class LinearMotion has three properties: speed, direction, and wrap.
The properties speed and direction are, we hope, obvious. The wrap property indicates whether the
actor should reenter the game area on the opposite side after leaving the game area. The two tasks
are constructors for creating LinearMotion objects. We could probably think of a few more handy
constructors for this class, but these two are all we need for this chapter. Let's start exploring the
implementation of the class LinearMotion by looking at these two constructors, shown in Listing 6-23.
Listing 6-23. LinearMotion.m (constructors)
+(id)linearMotionInDirection:(float)aDirection AtSpeed:(float)aSpeed{
LinearMotion* motion = [LinearMotion new];
[motion setDirection:aDirection];
[motion setSpeed:aSpeed];
return motion;
}
+(id)linearMotionRandomDirectionAndSpeed{
float direction = (arc4random()%100/100.0)*M_PI*2;
float speed = (arc4random()%100/100.0)*3;
return [LinearMotion linearMotionInDirection:direction AtSpeed:speed];
}
The constructor linearMotionInDirection:AtSpeed : simply creates a new LinearMotion object and
sets the two properties. The constructor linearMotionRandomDirectionAndSpeed creates random values
for direction and speed, and then simply calls the constructor linearMotionInDirection:AtSpeed :.
Listing 6-24 shows the rest of the implementation of the class LinearMotion .
Listing 6-24. LinearMotion.m
-(void)setSpeed:(float)aSpeed{
speed = aSpeed;
deltaX = cosf(direction)*speed;
deltaY = sinf(direction)*speed;
}
Search WWH ::




Custom Search