Game Development Reference
In-Depth Information
is responsible for actually drawing the Actor . In this example, these two objects—the actor and
the delegate —will be the same object, either a Bullet or a HealthBar . However, this is not a
requirement. I like to keep all the code related to an actor in the actor's class. The delegate could be
its own class responsible for drawing the actor. This would make sense if you wanted to use a single
VectorRepresentationDelegate to draw multiple types of actors. The implementation of the class
VectorActorView is very simple, as can be seen in Listing 7-10.
Listing 7-10. VectorActorView.m
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[delegate drawActor:actor WithContext:context InRect:rect];
}
In Listing 7-10, we see that the implementation is the class VectorActorView a single method, the
implementation of the task drawRect: . In this method, we get a reference to the current graphics
context by calling UIGraphicsGetCurrentContext and passing the context and the actor to the
delegate to be drawn in the CGRect specified. Let's now take a look at a specific example.
Drawing a HealthBar
As mentioned, the vector-based actors used in this example are their own delegates in terms of
drawing, so let's look at the HealthBar class again and see how it draws itself. See Listing 7-11.
Listing 7-11. HealthBar.m (drawActor:WithContext:InRect:)
-(void)drawActor:(Actor*)anActor WithContext:(CGContextRef)context InRect:(CGRect)rect{
CGContextClearRect(context,rect);
float height = 10;
CGRect backgroundArea = CGRectMake(0, self.radius-height/2, self.radius*2, height);
[self.backgroundColor setFill];
CGContextFillRect(context, backgroundArea);
CGRect healthArea = CGRectMake(0, self.radius-height/2, self.radius*2*percent, height);
[self.color setFill];
CGContextFillRect(context, healthArea);
}
In Listing 7-11, we start by calling CGContectClearRect. This erases any old content in the given
rect , getting us ready to do our real drawing. To draw the HealthBar , all we have to do is draw two
rectangles, one for the background and another on top of the background representing the current
percentage of the health bar. To draw a rectangular area (as apposed to drawing the edges of a
rectangle), we define a rect by calling CGRectMake . Then we specify the color to be used by calling
setFill on the UIColor object backgroundColor , which is a property of HealthBar .
 
Search WWH ::




Custom Search