Showing posts with label iphone game. Show all posts
Showing posts with label iphone game. Show all posts

Saturday, October 10, 2015

Custom UISwitch in iOS

I wanted to create Custom UISwitch in my iOS game. Initially I just waned to change size, font and color and for that I used UICustomSwitch from Hardy Macia found at here. It's quite easy to use and customisable, but then I wanted to switch to use custom image instead of standard one. For that I need to modify code a bit, below is the code which use custom image to create UISwitch. BTW this is how it looks


Header is same as original implementation, but I removed unnecessary properties and added left and right images required to display on and off images for switch.
@interface UICustomSwitch : UISlider {
    BOOL on;
    UIImageView* leftImage;
    UIImageView* rightImage;
 
    BOOL touchedSelf;
}

@property(nonatomic,getter=isOn) BOOL on;
@property (nonatomic, retain) UIImageView* leftImage;
@property (nonatomic, retain) UIImageView* rightImage;

- (void)setOn:(BOOL)on animated:(BOOL)animated;

@end
Now lets see implementation. Below is code for initialising the UISwitch with custom rect. You can also see we are adding On and Off image as left and right subview to switch.
-(id)initWithFrame:(CGRect)rect
{    
    if ((self=[super initWithFrame:rect])) {
 [self awakeFromNib];
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
 
    self.backgroundColor = [UIColor clearColor];
    
    [self setThumbImage:[Util imageNamed:@"switch"] 
        forState:UIControlStateNormal];
    [self setMinimumTrackTintColor:[UIColor clearColor]];
    [self setMaximumTrackTintColor:[UIColor clearColor]];
    
    self.minimumValue = 0;
    self.maximumValue = 1;
    self.continuous = NO;
 
    self.on = NO;
    self.value = 0.0;
 
    self.leftImage = [[UIImageView alloc] initWithFrame:self.frame];
    self.leftImage.image = [Util imageNamed:@"on"];
    [self addSubview: self.leftImage];
    [self.leftImage release];
    
    self.rightImage = [[UIImageView alloc] initWithFrame:self.frame];
    self.rightImage.image = [Util imageNamed:@"off"];
    [self addSubview: self.rightImage];
    [self.rightImage release];
}

Now you should be able to see UISwitch with custom images, we now need to add code required to on and off switch from code and change image accordingly.
- (void)setOn:(BOOL)turnOn animated:(BOOL)animated;
{
    on = turnOn;
 
    if (animated) {
 [UIView beginAnimations:@"UICustomSwitch" context:nil];
 [UIView setAnimationDuration:0.2];
    }
 
    if (on) {
 self.value = 1.0;
        self.rightImage.hidden = YES;
        self.leftImage.hidden = NO;
    } else {
 self.value = 0.0;
        self.rightImage.hidden = NO;
        self.leftImage.hidden = YES;
    }
 
    if (animated) {
 [UIView commitAnimations]; 
    }
}


Now finally we also have to add code to enable interaction.
- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [super endTrackingWithTouch:touch withEvent:event];
    touchedSelf = YES;
    [self setOn:on animated:YES];
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesBegan:touches withEvent:event];
    touchedSelf = NO;
    on = !on;
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
    [super touchesEnded:touches withEvent:event]; 
    if (!touchedSelf) {
 [self setOn:on animated:YES];
 [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}
That's it, I hope this will help.

Sunday, August 16, 2015

The Math Game for iOS

If you have read my previous posts, you might already know I was trying to learn Swift language. While doing so I tried to create a simple game.

Finally I was able to complete the app and was able to publish it as well. You can download app from here.


Below is demo of the game.

You can also get more information about app here.

Sunday, June 28, 2015

Posting score to Game Kit Leader board using swift

As you might already know, I recently started exploring Swift language and now I am trying out GameKit framework. While I have some experience in working with GameKit using Objective C. I wanted to do the same thing using swift. As such there are no API changes while using GameKit with Swift or Objective C. However there are some syntax change.

In this post, I will show how to Authenticate local player using GameKit framework and post score to LeaderBoard defined in iTune Connect Application setting.

Following is code snippet that shows how to Authenticate Local player. This function takes ViewController as argument. Login dialog will be displayed using this View controller. Rest will be taken care by GameKit framework.
func authenticateLocalPlayer(viewController: UIViewController) {
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    
    localPlayer.authenticateHandler = {(ViewController, error) -> Void in
        if((ViewController) != nil) {
            // 1 Show login if player is not logged in
            viewController.presentViewController(ViewController, animated: true, completion: nil)
        } else if (localPlayer.authenticated) {
            // 2 Player is already euthenticated & logged in, load game center
            self.isGameCenterEnabld = true                
        } else {
            // 3 Game center is not enabled on the users device
            self.isGameCenterEnabld = false
            println("Local player could not be authenticated, disabling game center")
            println(error)
        }
        
    }
    
}
Now we have authenticated local player. So when we are ready to post score to Leader Board. We can use below function. Here we are posting score to "defaultLeaderBoard". Which is identifier of Leader board defined in iTune connect App setting.

func submitScore( score: Int) {
    if( !isGameCenterEnabld ) {
        return;
    }
    
    var sScore = GKScore(leaderboardIdentifier: defaultLeaderBoard)
    sScore.value = Int64(score)
    
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    
    GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError!) -> Void in
        if error != nil {
            println(error.localizedDescription)
        } else {
            println("Score submitted")
            
        }
    })
}
That's it. Hope this will be useful.

Sunday, June 7, 2015

Performing Segue and Passing data in iOS

I was trying to learn how to perform view switching using Segue for UI created by StoryBoard. Using Segue is quite easy and convenient. You can create Segue from Interface Builder, which associate action to view. Like if you click some button then you can associate this click action with view switch and you can select which view to switch to. This all is quite simple and can be done using simple drag and drop.

In case you want to perform view switch manually without any user interaction, you can call "performSegueWithIdentifier", like below. Here once my game is finished, I am calling "GameOverSegue", which will switch view to GameOver view.
self.performSegueWithIdentifier("GameOverSegue", sender: self)
If you want to pass some data while performing Segue, your calling ViewController needs to override "prepareForSegue" function. In this function you can set data to called view. Like below, I want to pass score to my GameOver view.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if( segue.identifier == "GameOverSegue") {
        let gameOverVC: GameOverViewController = 
            segue.destinationViewController as! GameOverViewController;
        gameOverVC.setScore(self.score)
    }
}
Thanks, hope this will be helpful.

Friday, June 5, 2015

Hiding status bar in iOS8 using Swift

I recently started learning swift, while learning I started to create simple game. I wanted to make my game full screen, but I was unable to hide top status bar from Interface builder. No matter what I change that status bar was always visible.

Buf I found following code snippet, if you add this code in your View Controller file, you can easily hide status bar.
override func prefersStatusBarHidden() -> Bool {
    return true;
}
Following how my ViewController file looks after adding this code.
class ViewController: UIViewController {
        
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func prefersStatusBarHidden() -> Bool {
        return true;
    }
}
That's it. Hope this will be hopeful.

Saturday, December 20, 2014

Resolving "_clock$UNIX2003", referenced from" error

I was trying to build Unity 3D project for simulator SDK. I wanted to get different screen size screen shot. But when I tried to build it I got following build error.
_clock$UNIX2003", referenced from
I found one work around to resolve this issue. We need to add following patch to main.mm file.
#include <time.h>

// "_clock$UNIX2003", referenced from:
//Temporary hack for building Simulator Project for Unity
extern "C"
{
    clock_t
    clock$UNIX2003(void)
    {
        return clock();
    }
}
Once I added above patch build started working fine for me and I was able to run project on Simulator.

Saturday, September 13, 2014

Creating array of IBOutlet

Sometimes you want to enable/disable bunch of buttons together or perform other such activities on bunch of UI elements created using Interface Builder.

I recently needed to perform similar operation on bunch of button for iOS game I am working on. For this kind of operation, its easier to create array of IBOutlet which can be created using IBOutletCollection. Following is my code, which create IBOutletCollection of UIButtons and then enable/disbale them together.
@interface MyViewController : UIViewController {
    IBOutletCollection(UIButton) NSArray *buttons;
}
in MyViewController.m, we can use buttons as below.
-(void) enableUI:(BOOL) enable {    
    for( UIButton* button in buttons){
        button.enabled = enable;
    }    
}
Only thing missing now is, connecting UIButtons created using Interface Builder to IBoutletCollection. We need to do this from Interface Builder, process is similar to connecting UI Elements from Interface Builder to IBOutlet.

Following snaps describes the required process. I created three buttons on view.


You can connect IBoutletCollection to UIButton as shown in below snap.


And you can repeat above process to connect more UIButton with IBOutletCollection.

That's it.

Friday, January 7, 2011

Dragon Killer Tien Len 13 game for iPhone, iPod

Sometime ago I was working with a friend to create Tien Len game for iPhone. Now that game is live on Apple app store.

Tien Len (also known as Thirteen, Killer, & VC) is a popular & very addicting card game that is played around the world.

Each player is given 13 cards, and the objective is to get rid of your cards before your opponents. The lowest card (3 of spades) is played to start the game and then players take turns using strategy to beat their opponent’s hand in multiple rounds with singles, doubles, triples, straights, and bombs. Suit rank (spades<4<5 … <2) determines which hand is higher than the other.

Please visit iTunes or App store for more information and download.

Following are few snaps from game.






Following is video from game.

Tuesday, July 27, 2010

Detecting Long press( Tap and hold) on iPhone application

I was creating one game for iPhone and I required to detect Tap and Hold (Long press ) gesture in application. After trying a bit and reading some documentation, I found following solution. Solution is to perform Selector with some delay, and cancel Selector if touch has ended before enough time is passed.

Following is code from my application.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch began");
[self performSelector:@selector(longTap) withObject:nil afterDelay:1.0];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch ended");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touches moved");
[NSObject cancelPreviousPerformRequestsWithTarget:self 
selector:@selector(longTap) object:nil];
}

-(void) longTap 
{
NSLog(@"handle long tap..");
}

Hope this helps...