Game Development Reference
In-Depth Information
In Figure 5-10 , on the left we see the game area and on the right is the CGRect that describes the
actorView 's frame . The circle on the left is an Actor02 that needs to be converted into CGRect on
actorView . We start by figuring out the origin of the GCFrame by first finding the upper-left point of the
Actor02 . We find the X value of the upper-left point by subtracting the radius of the Actor02 from
the Actor02 's center X value. To find the Y value, we subtract the radius from the Actor02 's center
Y value. To convert these points into the coordinate space of actorView , we simply multiple by the
X value of the upper left point by xFactor and multiple the Y value by yFactor . The values xFactor
and yFactor are the ratios between the gameAreaSizes width and height and the actorView 's frame 's
width and height. To find the size of actorView 's frame, we simply multiply the radius by xFactor and
yFactor to find the width and height.
When the user touches the UIView actorView , we have to do this process in reverse: convert
the point on the actorView to a point with our game space. This conversion happens in the task
tapGesture: , as shown in Listing 5-18.
Listing 5-18. Example02Controller.h (tapGuesture:)
- (void)tapGesture:(UIGestureRecognizer *)gestureRecognizer{
UITapGestureRecognizer* tapRecognizer = (UITapGestureRecognizer*)gestureRecognizer;
CGPoint pointOnView = [tapRecognizer locationInView:actorView];
float xFactor = actorView.frame.size.width/self.gameAreaSize.width;
float yFactor = actorView.frame.size.height/self.gameAreaSize.height;
CGPoint pointInGame = CGPointMake(pointOnView.x/xFactor, pointOnView.y/yFactor);
[viper setMoveToPoint:pointInGame];
}
In Listing 5-18, we find where the user touched by calling locationInView: on tapRecognizer
and passing in actorView and storing the result in pointOnView . After recalculating xFactor and
yFactor values, we simply divide pointOnView 's X and Y values by xFactor and yFactor , giving us
pointInGame . Using this value we simply, set the moveToPoint property of viper with pointInGame .
To wrap up this example, let's take a look at the code that changes the size of actorView , as shown
in Listing 5-19.
Listing 5-19. Example02Controller.m (sliderValueChanged:)
- (IBAction)sliderValueChanged:(id)sender {
UISlider* slider = (UISlider*)sender;
float newWidth = [slider value];
float newHeight = gameAreaSize.height/gameAreaSize.width*newWidth;
CGRect parentFrame = [[actorView superview] frame];
float newX = (parentFrame.size.width-newWidth)/2.0;
float newY = (parentFrame.size.height-newHeight)/2.0;
CGRect newFrame = CGRectMake(newX, newY, newWidth, newHeight);
[actorView setFrame:newFrame];
}
Search WWH ::




Custom Search