Introduction
The is also a very simple article for beginners ready to create games in iPhone. Here I will use very simple logic to do animation. Here I will add one more functionality of games, "Sound effect" on specific events of an action. In this article I will use one custom button and two image views from outlets but one image view in code. Here I will make a very simple or interesting game "GunFire". Here we use a gun which is fired at a bug; when we click on a gun it fires a bullet at bugs. On a single fire, one bug disappears from view and another two appear in a suspended state; in other words we can say they look injured. In the next fire a second bug also disappears and in the last fire the last (third) bug also disappears from view. Now one bug created by an image view appears continuously until you will play the game. Here we add a sound file (like Gun fire) for a specific action, which provides the sound of a bug dying, played as background music until you play the game. It is a very simple logic for leaner animation.
For more detail use the following procedure.
Step 1
Open Xcode by double-clicking on it.
Step 2
Create a New XCode Project by clicking on it.
Step 3
Now select Single View Application and click on Next.
Step 4
Now provide your Product Name and Company Identifier then click on Next.
Step 5
Select the location where you want to save your project and click on Create.
Step 6
Here we write code; see:
AppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class BasicSoundsViewController;
@interface BasicSoundsAppDelegate : NSObject <UIApplicationDelegate, AVAudioPlayerDelegate> {
UIWindow *window;
BasicSoundsViewController *viewController;
AVAudioPlayer *_backgroundMusicPlayer;
BOOL _backgroundMusicPlaying;
BOOL _backgroundMusicInterrupted;
UInt32 _otherMusicIsPlaying;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet BasicSoundsViewController *viewController;
- (void)tryPlayMusic;
@end
AppDelegate.m
#import "BasicSoundsAppDelegate.h"
#import "BasicSoundsViewController.h"
@implementation BasicSoundsAppDelegate
@synthesize window;
@synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Set up the audio session
// See handy chart on pg. 55 of the Audio Session Programming Guide for what the categories mean
// Not absolutely required in this example, but good to get into the habit of doing
// See pg. 11 of Audio Session Programming Guide for "Why a Default Session Usually Isn't What You Want"
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"background-music-aac" ofType:@"caf"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
[_backgroundMusicPlayer setDelegate:self];// We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
_backgroundMusicInterrupted = YES;
_backgroundMusicPlaying = NO;
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
if (_backgroundMusicInterrupted) {
[self tryPlayMusic];
_backgroundMusicInterrupted = NO;
}
}
- (void)applicationDidBecomeActive:(NSNotification *)notification {
[self tryPlayMusic];
}
- (void)tryPlayMusic {
// Check to see if iPod music is already playing
UInt32 propertySize = sizeof(_otherMusicIsPlaying);
AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &_otherMusicIsPlaying);
// Play the music if no other music is playing and we aren't playing already
if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
[_backgroundMusicPlayer prepareToPlay];
[_backgroundMusicPlayer play];
_backgroundMusicPlaying = YES;
}
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
@end
ViewController.h
import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
@interface BasicSoundsViewController : UIViewController {
SystemSoundID _pewPewSound;
bool bugDead;
}
@property(strong,nonatomic) IBOutlet UIImageView *basketTop;
@property (strong,nonatomic) IBOutlet UIImageView *basketBottom;
@property (strong,nonatomic) IBOutlet UIImageView *Bugblaster;
@property (strong,nonatomic) IBOutlet UIImageView *bug;
@property (strong,nonatomic) IBOutlet UIImageView *bug1;
- (IBAction)spaceshipTapped:(id)sender;
- (void)fireBullet;
@end
ViewController.m
#import "BasicSoundsViewController.h"
@implementation BasicSoundsViewController
@synthesize bug1;
@synthesize bug;
@synthesize basketTop;
@synthesize basketBottom;
@synthesize Bugblaster;
- (void)viewDidLoad {
[super viewDidLoad];
CGRect basketTopFrame = basketTop.frame;
basketTopFrame.origin.y = -basketTopFrame.size.height;
CGRect basketBottomFrame = basketBottom.frame;
basketBottomFrame.origin.y = self.view.bounds.size.height;
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
basketTop.frame = basketTopFrame;
basketBottom.frame = basketBottomFrame;
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
bug1 = [[UIImageView alloc]init];
bug1.frame = CGRectMake(20,30 , 80, 100);
bug1.image = [UIImage imageNamed:@"Bugblaster.png"];
[self.view addSubview:bug1];
[self moveToLeft:nil finished:nil context:nil];
NSString *pewPewPath = [[NSBundle mainBundle] pathForResource:@"pew-pew-lei" ofType:@"caf"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((CFURLRef)pewPewURL, &_pewPewSound);
}
- (void)moveToLeft:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if (bugDead) return;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:2.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(faceRight:finished:context:)];
bug.center = CGPointMake(75, 200);
bug1.center = CGPointMake(85, 100);
Bugblaster.center = CGPointMake(230, 250);
[UIView commitAnimations];
}
/*
- (void)moveToRight {
[UIView animateWithDuration:1.0
delay:2.0
options:0
animations:^{
bug.center = CGPointMake(230, 250);
}
completion:^(BOOL finished) {
[UIView animateWithDuration:1.0
delay:0
options:0
animations:^{
bug.transform = CGAffineTransformMakeRotation(0);
} completion:^(BOOL finished) {
[self moveToLeft];
}];
}];
}
- (void)moveToLeft {
[UIView animateWithDuration:1.0
delay:2.0
options:0
animations:^{
bug.center = CGPointMake(75, 200);
}
completion:^(BOOL finished) {
[UIView animateWithDuration:1.0
delay:0
options:0
animations:^{
bug.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
[self moveToRight];
}];
}];
}
*/
- (void)faceRight:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if (bugDead) return;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:0.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(moveToRight:finished:context:)];
bug.transform = CGAffineTransformMakeRotation(M_PI);
bug1.transform = CGAffineTransformMakeRotation(M_PI);
Bugblaster.transform = CGAffineTransformMakeRotation(M_PI);
[UIView commitAnimations];
}
- (void)moveToRight:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if (bugDead) return;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:2.0];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDidStopSelector:@selector(faceLeft:finished:context:)];
bug.center = CGPointMake(230, 250);
bug1.center = CGPointMake(200, 150);
Bugblaster.center = CGPointMake(75, 200);
[UIView commitAnimations];
}
- (void)faceLeft:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if (bugDead) return;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:0.0];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDidStopSelector:@selector(moveToLeft:finished:context:)];
bug.transform = CGAffineTransformMakeRotation(0);
bug1.transform = CGAffineTransformMakeRotation(0);
Bugblaster.transform = CGAffineTransformMakeRotation(0);
[UIView commitAnimations];
}
- (IBAction)spaceshipTapped:(id)sender {
AudioServicesPlaySystemSound(_pewPewSound);
[UIView beginAnimations:@"animateImageOff" context:NULL]; // Begin animation
[bug setFrame:CGRectOffset([bug frame], 0, -bug.frame.size.height)];
[bug1 setFrame:CGRectOffset([bug1 frame], 0, -bug1.frame.size.height)];
[Bugblaster setFrame:CGRectOffset([bug frame], 0, -Bugblaster.frame.size.height)];// Move imageView off screen
[UIView commitAnimations];
[self fireBullet];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
AudioServicesDisposeSystemSoundID(_pewPewSound);
[super dealloc];
}
#pragma mark These are just methods for fun :P
- (void) animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIImageView *bullets = (UIImageView *)context;
[bullets removeFromSuperview];
}
- (void)fireBullet {
UIImageView *bullets = [[[UIImageView alloc] initWithFrame:CGRectMake(84, 256, 147, 29)] autorelease];
bullets.image = [UIImage imageNamed:@"bullets.png"];
[self.view addSubview:bullets];
[self.view sendSubviewToBack:bullets];
[UIView beginAnimations:@"shoot" context:bullets];
CGRect frame = bullets.frame;
frame.origin.y = -29;
bullets.frame = frame;
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
bugDead = true;
[UIView animateWithDuration:0.7
delay:0.0
options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionBeginFromCurrentState
animations:^{
bug.transform = CGAffineTransformMakeScale(1.25, 0.75);
}
completion:^(BOOL finished) {
[UIView animateWithDuration:2.0
delay:2.0
options:0
animations:^(void){Bugblaster.center = CGPointMake(90, 300);}
completion:NULL];{
bug1.alpha = 0.0;
} completion:^(BOOL finished) {
[bug1 removeFromSuperview];
bug1 = nil;
};
}];
}
@end
ViewController.Xib
Step 7
Now select the iPhone platform to see output in the Simulator.
Output
Splash in iPhone:
Output1 in iPhone:
Now a window will be opened using animation.
Output2 in iPhone:
Output3 in iPhone:
Here we see three bugs.
Output4 in iPhone:
Now when we fire a single shot one bug dies and the rest look injured.
Output5 in iPhone:
In the third shot the last bug also dies.
Output6 in iPhone:
At last I will Capture a gunshot.