<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iPhone Programming Tutorials &#187; ebennett</title>
	<atom:link href="/author/ebennett/feed/" rel="self" type="application/rss+xml" />
	<link>http://icodeblog.com</link>
	<description>iPhone Programming Tutorials</description>
	<lastBuildDate>Tue, 19 Nov 2013 19:34:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>DICE+, rocketships and a giveaway.</title>
		<link>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/</link>
		<comments>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/#comments</comments>
		<pubDate>Sat, 06 Jul 2013 00:18:39 +0000</pubDate>
		<dc:creator><![CDATA[ebennett]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Dice+]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[rocketship]]></category>
		<category><![CDATA[space]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=4414</guid>
		<description><![CDATA[<a href="/wp-content/uploads/2013/07/screenShot.jpg"></a>
I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: center"><img class="alignleft size-medium wp-image-4469" alt="Dice+Image" src="/wp-content/uploads/2013/07/Dice+Image-300x300.jpg" width="300" height="300" /><a href="/wp-content/uploads/2013/07/screenShot.jpg"><img class="alignleft size-medium wp-image-4529" alt="screenShot" src="/wp-content/uploads/2013/07/screenShot-225x300.jpg" width="225" height="300" /></a></p>
<p>I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is fair, and each face can display a wide range of colors due to the red, green and blue LEDs backlighting every side. Balanced to match any standard 6 sided die performance, the DICE+ brings back some of the tactile fun of playing games on digital devices. Although not quite out on the market as of this writing, developers can download the SDK, order kits and start developing. The developers over at DICE+ have also set aside a kit to give away to one of the readers of this post. The first 6 readers who reply to this post and correctly lists all sensors available, will be entered in the drawing. A DICE+ will then be rolled, a winner selected from those replies and sent one of the DICE+ developer kits. Now that I have had some fun, I thought I would share, and show how easy it was to use.</p>
<p>In the following tutorial, I have designed a simple 2 player game in which you are trying to be the first player to get your ship into space. Each player takes a turn rolling the die, the first player to reach 25 is the winner. With the addition of some simple UIView animations to animate our player ships and space background, the race to space can begin. Link to project file and assets are at the end of this post.</p>
<p>First lets create a new, single view, portrait oriented project for iPad called &#8216;RaceToSpace&#8217; using ARC (Automatic Reference Counting).  After downloading the DICE+ SDK from the website, drag and drop the framework into your project, add the &#8216;CoreBluetooth&#8217;, and QuartzCore frameworks. For DICE+, You will also have to add &#8216;-all_load&#8217; to your projects build settings, under other linker commands. In Interface Builder, add a UIImageView to your view, setting its size and origin to the following x=0, y=-1024, width=768 and height=2048. Press your editors double column view button, and while holding the control button, left mouse click the newly added UIImageView and link to your .h file creating an IBOutlet reference called &#8216;spaceBackground&#8217;. Add a Play button to start the game, a label at the bottom to show bluetooth connection info and turn status, and 2 labels at the top for displaying player scores. Link all of these to your .h file as you did with the space background UIImageView, using these corresponding names; playButton, status, player1Score, player2Score. You will also need to right click on the PLAYBUTTON, and link the &#8216;touch up inside&#8217; action onto your ViewController.m file and name it &#8216;Play&#8217;. Now that the basic building blocks are setup, we can get to configuring the software for use with your die.</p>
<p>In your ViewController .h, add the following code to match.</p>
<div class="wp_syntax">
<pre><span style="color: #800000"> 
#impor</span>t &lt;UIKit/UIKit.h&gt;
<span style="color: #800000">#import</span> &lt;DicePlus/DicePlus.h&gt;
<span style="color: #800000">#import</span> "Player.h"

<span style="color: #800000">@interface</span> ViewController : UIViewController <span style="color: #000080">&lt;DPDiceManagerDelegate&gt;</span>
{
    <span style="color: #000080">DPDiceManager</span>* diceManager;
    <span style="color: #000080">DPDie</span>* availableDie;
    <span style="color: #000080">DPDie</span>* connectedDie;
}
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player1Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player2Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIImageView</span> *spaceBackground;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *status;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">NSArray</span> *players;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">Player</span> *currentPlayer;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIButton</span> *play;

@end</pre>
</div>
<p>In your ViewController.m, add the following code to your viewDidLoad method. This initializes the dice manager, sets the DEV KEY with the <b>[diceManager startScanning]</b> command, and starts scanning for available devices. Also add the #define MaxPoints 25. This defines the winning score.</p>
<div class="wp_syntax">
<pre><span style="color: #660000"> 
#define MaxPoints 25</span>

<span style="color: #993300">@implementation</span> ViewController

- (<span style="color: #993300">void</span>)viewDidLoad
{
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>
    if (connectedDie != nil) {
        return;
    }
    availableDie = nil;
    diceManager = [DPDiceManager sharedDiceManager];
    diceManager.delegate = self;

<span style="color: #008000">    //DICE+ generic development key.
</span>    uint8_t key[8] = {0x83, 0xed, 0x60, 0x0e, 0x5d, 0x31, 0x8f, 0xe7};
    [diceManager setKey:key];

    <span style="color: #008000">//Start scanning for an available DICE+</span>.
    [diceManager startScan];
    self.status.text = @"Searching for DICE+...";
}</pre>
</div>
<p>If you notice the error pertaining to the #import Player.h and the player object, we will be adding that in a moment so you can ignore that for now. We do need to add some delegate calls so we can be notified of a DICE+ connection, and some to receive results when the die is rolled. I will also explain in detail the contained code when we walk thru the functionality of the game.</p>
<div class="wp_syntax">
<pre> 
- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error
{
    <span style="color: #008000">//Roll was valid</span>
    if (roll.flags == <span style="color: #993366">DPRollFlagOK</span>) {
        <span style="color: #008000">//Stop roll updates just to make sure wrong player doesnt mistakenly roll DICE+.</span>
        [connectedDie stopRollUpdates];
        <span style="color: #008000">//Convert roll result (1-6) to binary mask equivalent</span>
        int mask = 1 &lt;&lt; (roll.result-1);
<span style="color: #008000">        //Blink the top face green showing roll result. DICE+ uses a binary mask for determinning which face, or faces to light.
</span>        [connectedDie startBlinkAnimationWithMask:mask priority:0 r:0 g:255 b:0 onPeriod:100 cyclePeriod:50 blinkCount:5];
        <span style="color: #008000">//Move player ship</span>
        [self moveCurrentPlayer:roll.result];

    } else if (roll.flags == <span style="color: #993366">DPRollFlagTilt</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll Tilted";
<span style="color: #008000">        //Blink DICE+ faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    } else if (roll.flags == <span style="color: #993366">DPRollFlagTooShort</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll too short";
<span style="color: #008000">        //Blink dice plus faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    }
}

#pragma mark - DPDiceManagerDelegate methods
- (<span style="color: #993300">void</span>)centralManagerDidUpdateState:(<span style="color: #000080">CBCentralManagerState</span>)state
{
<span style="color: #008000">    // See CBCentralManagerDelegate documentation for info about CBCentralManager state changes
</span>}

- (<span style="color: #993300">void</span>)diceManagerStoppedScan:(<span style="color: #000080">DPDiceManager</span> *)manager
{
<span style="color: #008000">    //Scanning has stopped, restart scan if no available die was found.
</span>    if (availableDie == nil) {
        [diceManager startScan];
        self.status.text = @"Searching for DICE+...";
    }
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDiscoverDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //A DICE+ die was found, not connected yet.
</span>    availableDie = die;
    availableDie.delegate = (id)self;

    [diceManager stopScan];
<span style="color: #008000">    //Attempt to connect to available DICE+ found.
</span>    [diceManager connectDie:availableDie];

    self.status.text = @"Connecting DICE+...";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didConnectDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //Available DICE+ connected and is ready for play.
</span>    availableDie = nil;
    connectedDie = die;
    connectedDie.delegate = (id)self;
    self.status.text = @"Press play to begin.";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager failedConnectingDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ failed connection attempt.
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Connection failed... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDisconnectDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ disconnected
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Die disconnected... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)dieFailedAuthorization:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ authorization failed.
</span>    self.status.text = @"Failed authorization";
}</pre>
</div>
<p>The DICE+ is well documented and there are quite a few delegate methods that can be used depending on which sensor you issue a startUpdate too.</p>
<p>We&#8217;ll go back to the functions of the game a little later on in the post, for now lets look at whats happening when connecting to the die.</p>
<p>After the app has started scanning for an active die and one has been found, the dice manager delegate , didDiscoverDie, will be called and the scanning is stopped using <b>[diceManager stopScan]</b>. Since we don&#8217;t know that we can successfully connect to the die, only that one is available, we store the returned found die as availableDie, then attempt a connection with it. If no available dice were found and the scanner times out (after 12 seconds), diceManagerStoppedScan: will get called. In our example we simply restart the scanning process and scan again.</p>
<p>Upon a successfull connection, dice manager didConnectDie delegate method is called. Since we want to differentiate between an available die and our successfully connected die, connectedDie is assigned and used for the rest of the games life cycle, and availableDie is nilled out. If for some reason there is an issue connecting to the available die, &#8216;failedConnectingDie:&#8217; is called. If a die is connected and looses that connection for some reason, the diceManager &#8216;didDisconnectDie:&#8217; is called. In this example a scan is started again to try and regain a connection.</p>
<p>Once we have a connected die, it is easy to start the various sensor updates and listen for their delegate calls. For this game, we will only worry about <b>[connectedDie startRollUpdates]</b>, <b>[connectedDie stopRollUpdates]</b>, and the corresponding delegate methods to receive the roll response once a valid roll is done.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error</pre>
</div>
<p>The value of the roll is returned in roll.result with roll state in roll.flag that gives information about the roll itself. <span style="color: #993366">DPRollFlagOK</span> is returned with a valid roll, <span style="color: #993366">DPRollFlagTilt</span> is returned if the die has landed on a tilt, and <span style="color: #993366">DPRollFlagTooShort</span> if not enough time was taken to make the roll. These flags are part of the anti cheat error checking done within the die.</p>
<p>As we add the functionality of the game, you will also see how easy it is to change and animate the LEDs for each face once a roll is completed, or for any other reason you may need.</p>
<p>For the actual gameplay we will be adding 6 new methods but first we need to create a player object to represent each of our 2 players. Right click on the RaceToSpace folder in the left hand, project navigator pane and select new file. Create a new subclass of NSObject and name it Player.</p>
<p>Add the following to the Player.h,</p>
<div class="wp_syntax">
<pre><span style="color: #993300">@interface</span> Player : <span style="color: #000080">NSObject</span>

<span style="color: #993300">@property</span>(nonatomic, retain) <span style="color: #000080">UIImage</span> *shipImage;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> score;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> playerNumber;

- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;

@end</pre>
</div>
<p>and this to your Player.m,</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;
{
    self = [super init];
    if (self) {
<span style="color: #008000">        // Initialization code
</span>        self.shipImage = shipImage;
        self.score = 0;
    }
    return self;
}</pre>
</div>
<p>Now we need to create the 2 players, do this at the beginning of your viewDidLoad, just after the call to super. Each player is created and assigned a player number, a UIImageView is also created to display the players ship, placed at their start positions on the screen and added to the view. By setting the tag of each of these UIImageViews to the players number, we can be sure to move the correct ship for the player. Initialize our player reference NSArray with both of our players..</p>
<div class="wp_syntax">
<pre> 
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>    
<span style="color: #008000">    //Setup Player 1
</span>    <span style="color: #000080">Player</span> *player1 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip1"]];
    player1.playerNumber = 1;
    UIImageView *player1ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player1ship.contentMode = UIViewContentModeCenter;
    player1ship.image = player1.shipImage;
    player1ship.center = CGPointMake(192, 928);
    player1ship.tag = player1.playerNumber;
    [self.view addSubview:player1ship];

<span style="color: #008000">    //Setup Player 2
</span>    <span style="color: #000080">Player</span> *player2 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip2"]];
    player2.playerNumber = 2;
    UIImageView *player2ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player2ship.contentMode = UIViewContentModeCenter;
    player2ship.image = player2.shipImage;
    player2ship.center = CGPointMake(576, 928);
    player2ship.tag = player2.playerNumber;
    [self.view addSubview:player2ship];</pre>
</div>
<p>Add some code to our Play button action and add these remaining methods to you ViewController.m and we will take a quick walk thru of the game.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">IBAction</span>)play:(<span style="color: #000080">id</span>)sender
{
<span style="color: #008000">    //Rest players score to 0 in case this is a <span style="color: #000080">replay.
</span></span>    self.play.hidden = YES;
    [self setupPlayer];
}

- (<span style="color: #993300">void</span>)setupPlayer
{
    if (!self.currentPlayer){
<span style="color: #008000">        //Its a new game, make current player, player 1.
</span>        self.currentPlayer = [self.players objectAtIndex:0];
    } else {
<span style="color: #008000">            //Switch between players
</span>            if (self.currentPlayer.playerNumber == 1){
<span style="color: #008000">                //Make current player, player 2.
</span>                self.currentPlayer = [self.players objectAtIndex:1];
            } else {
<span style="color: #008000">                //Make current player, player 1.
</span>                self.currentPlayer = [self.players objectAtIndex:0];
            }
        }
    self.status.text = [NSString stringWithFormat:@"Player %i's turn", self.currentPlayer.playerNumber];

<span style="color: #008000">    //Start DICE+ roll updates for current player.
</span>    [connectedDie startRollUpdates];
}

- (<span style="color: #993300">void</span>)prepareForNewGame
{
<span style="color: #008000">    //Set player scores to 0 and reset ships to start position.
</span>    for (Player *p in self.players){
        p.score = 0;
        UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:p.playerNumber];
        playerShip.center = CGPointMake(playerShip.center.x, 928);
    }

<span style="color: #008000">    //Reset some labels
</span>    self.play.hidden = NO;
    self.player1Score.text = @"0 points";
    self.player2Score.text = @"0 points";
    self.status.text = @"Press play to begin.";

<span style="color: #008000">    //Animate background back to start position
</span>    [UIView animateWithDuration:.25 animations:^{
        self.spaceBackground.center = CGPointMake(384, 0);
    }];

<span style="color: #008000">    //Set current player to nil so new game will start with player 1.
</span>    self.currentPlayer = nil;
}

- (<span style="color: #993300">BOOL</span>)currentPlayerIsWinner
{
<span style="color: #008000">    //check if current player has matched, or exceeded max points
</span>    if (self.currentPlayer.score &gt;= MaxPoints){
        return YES;
    }
    return NO;
}

- (<span style="color: #993300">void</span>)moveCurrentPlayer:(<span style="color: #000080">NSInteger</span>)rollValue
{
<span style="color: #008000">    //Get UIImageView for players ship and animate p the screen.
</span>    UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:self.currentPlayer.playerNumber];

<span style="color: #008000">    //Calculate appropriate distance to travel based on MaxPoints, so winner is always near top of screen.
</span>    int offset = (1024 - rintf(1024/6))/MaxPoints;
    int distance = rollValue * offset;
    self.currentPlayer.score = self.currentPlayer.score + rollValue;

    if ([self currentPlayerIsWinner]) {
<span style="color: #008000">        //Current player has won. Do something.
</span>        NSString *winnerText = [NSString stringWithFormat:@"Congratulations player %i, you are the Winner!", self.currentPlayer.playerNumber];
        UIAlertView *winnerNotify = [[UIAlertView alloc] initWithTitle:@"WINNER!!" message:winnerText delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [winnerNotify show];
        self.status.text = @"We have a WINNER!";

<span style="color: #008000">        //Fly the winning ship the rest of the way off the screen.
</span>        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, -200);
        }];
        return;
    } else {
        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, playerShip.center.y - distance);
        }];
        if (self.currentPlayer.playerNumber == 2){
            self.player2Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self slideBackground:distance];
        } else {
            self.player1Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self setupPlayer];
        }
    }
}

- (<span style="color: #993300">void</span>)slideBackground:(<span style="color: #000080">NSInteger</span>)distance
{
<span style="color: #008000">    //Check if background is able to scroll any further, if so scroll up distace value.
</span>    if (self.spaceBackground.center.y + distance &lt; 1024){
        [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.spaceBackground.center = CGPointMake(384, self.spaceBackground.center.y + distance);
        } completion:^(BOOL finished) {
<span style="color: #008000">            //Setup next player when animation is done.
</span>            [self setupPlayer];
        }];
    }
}</pre>
</div>
<p>When the play button is pressed and the <b>- (IBAction)play:(id)sender</b> callback is called, the play button is hidden and <b>[self setupPlayer]</b> is called. SetupPlayer, checks to see if self.currentPlayer uninitialized, if so then it represents a new game and currentPlayer is assigned as Player1 from index 0 of the Players reference array. We set the text of our connection status label to state that it is player 1&#8217;s turn and the DICE+ roll updates are started with <b>[connectedDie startRollUpdates]</b>; The game is now waiting for player 1 to roll. Once a valid roll is made, the <b>die: didRoll:</b> delegate method is called. With a successful roll.flag of DPRollFlagOK a few things happen. Dependent on the value of roll.result, an int called mask is set to a specific value. This mask value is how we tell the DICE+ which face or faces to light up.</p>
<p>&nbsp;</p>
<p>A quick explanation of the  mask value. If you think of a 6 bit binary number, adding each decimal value of the bits (or faces) you want lit up, this total number is the mask. For example if I wanted the number 2 face to light,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>0    1    0    0    0    0  (binary mask)</p>
<p>Number for the mask would be 2.</p>
<p>If you wanted faces 1, 2 and 3 to light up, the mask would be,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>1    1    1     0    0    0  (binary mask)</p>
<p>Number for mask would be 6.</p>
<p>All faces would be represented by the number 63.</p>
<p>&nbsp;</p>
<p>We can pass this mask, as well as color and various other info to the die in a couple of different methods used to blink and fade the lights on and off. In our game, when a roll is invalid (either tilted or too short), an animation is used to blink all the faces red for a short time. Upon a valid roll, the face of the rolled value is blinked green.</p>
<p>After a successful roll, the roll updates of the die are stopped, this may not be necessary but may stop any accidental rolls and turn changes. <b>[self moveCurrentPlayer:roll.result]</b> is then called, passing along the rolled die value. This value is used in moveCurrentPlayer to move the current players ship up the screen (players UIImageView is found in the view by its tag), added to their current score and checks to see if the current player is the winner <b>[self currentPlayerIsWinner]</b> and returns a TRUE/FALSE. If the current player is not the winner, the game continues to the next step. If this is player2, then the background image is slid down the screen an appropriate amount in <b>[self slideBackground:roll.result]</b> using a simple UIView animation. Whether the background needed sliding or not, the next step is <b>[self setupPlayer]</b>.</p>
<p><b>[self setupPlayer]</b> determines that the currentPlayer is valid, checks the player&#8217;s number of the current player, and switches current player to the other player, roll updates are started once again and the next player can take their turn. In <b>[self moveCurrentPlayer]</b> once a player reaches, or passes, 25 (as defined at the top of ViewController.m in MaxPoints) that triggers the winning phase. One slight addition to add to our game is to show a UIAlertView when a player wins and inform us when it is dismissed so we can reset the game.</p>
<p>Add to your ViewController.h so we can know when the user dismisses the winning text and delegate call for the alertView,</p>
<div class="wp_syntax">
<pre>@interface ViewController : UIViewController &lt;DPDiceManagerDelegate, <span style="color: #0000ff">UIAlertViewDelegate</span>&gt;</pre>
</div>
<p>and the following in your ViewController.m so we know when it is dismissed.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)alertView:(<span style="color: #000080">UIAlertView</span> *)alertView didDismissWithButtonIndex:(<span style="color: #000080">NSInteger</span>)buttonIndex
{
<span style="color: #008000">    //Once cancel is pressed on the alertview, prepare for new game.
</span>    [self prepareForNewGame];
}</pre>
</div>
<p>On a winning score the UIAlertView is displayed, status text is updated and the winning ship is flown the rest of the way of the screen. When the player dismisses the UIAlertView popup, <b>[self prepareForNewGame]</b> is called. Within that method, variables are reset, ships are set back to their starting positions and currentPlayer is set to nil. With a press of the Play button once again, the game play can start again.</p>
<p>I realize a lot more could be added, more in-depth animations could be done and special instances such as rolling the same number twice in a row to initiate special rules but since this was more about attaching and using the DICE+, I will leave those upgrades and additions to you. Hope you enjoyed this tutorial, I have enjoyed getting to test out this new product and look forward to what may come of it. Thanks.</p>
<p>Here is the link to the <a title="Race to Space image files." href="/wp-content/uploads/2013/07/RaceToSpaceAssets.zip">images</a> used in the game, and here is a <a title="Race To Space" href="https://github.com/B-Sides/RaceToSpace" target="_blank">link</a> to the GitHub repository. In order to ensure the latest SDK, you will need to <a title="Developer link" href="http://developers.dicepl.us" target="_blank">download the DICE+ SDK</a> (the version of the SDK depends on the firmware loaded on the Die) separately, and drag the DicePlus.framework file into the project.</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Adding an OpenGL ES view to your project using NinevehGL</title>
		<link>http://icodeblog.com/2012/09/07/3856/</link>
		<comments>http://icodeblog.com/2012/09/07/3856/#comments</comments>
		<pubDate>Fri, 07 Sep 2012 09:00:34 +0000</pubDate>
		<dc:creator><![CDATA[ebennett]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[gl]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[opengl es]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3856</guid>
		<description><![CDATA[Recently I came across an openGL ES 2.0 engine that made setup, displaying and animating of 3D objects a breeze, called <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a>.  This 3D engine has many great features including a full multithreading environment, to keep the main run loop free during object rendering,  motion tweening, object groupings, custom lighting, materials and textures, custom shader support,  and native support for augmented reality, just to name a few. Another major benefit is the ability to import both wavefront  ...]]></description>
				<content:encoded><![CDATA[<p>Recently I came across an openGL ES 2.0 engine that made setup, displaying and animating of 3D objects a breeze, called <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a>.  This 3D engine has many great features including a full multithreading environment, to keep the main run loop free during object rendering,  motion tweening, object groupings, custom lighting, materials and textures, custom shader support,  and native support for augmented reality, just to name a few. Another major benefit is the ability to import both wavefront (.obj) and Collada (.dae) files. This framework is very easy to use, powerful,  and can be utilized in many different ways.</p>
<p><iframe src="http://player.vimeo.com/video/48964690" height="758" width="500" allowfullscreen="" frameborder="0"></iframe></p>
<p><a href="http://vimeo.com/48964690">IOS openGL rotating Earth using NinevehGL</a> from <a href="http://vimeo.com/user13362310">Erick Bennett</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>In this tutorial I am going to show you how to easily, and effectively add an openGL ES 2.0 3D view into your project, and display a fully rendered, rotating 3D earth. The model assets are available <a title="openGLView assets" href="/wp-content/uploads/2012/09/openGLViewAssets.zip">here</a>, and include the object and texture. These assets are also available in the <a title="openGLview Project file." href="/wp-content/uploads/2012/09/openGLview.zip">project ZIP file</a>, available thru the link at the end of this tutorial.</p>
<p>Download and install the <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL framework</a>.</p>
<p>Since we want to add this view into an existing project and understand how the engine functions, lets create a new single-view project to start. Although <a title="NinevehGL" href="http://nineveh.gl" target="_blank">NinevehGL</a> can just as easily be setup thru interface builder, we will be adding this view programmatically. For this exercise, it does not matter if you select storyboard or XIB for the new project.</p>
<p>To begin with there are a few frameworks we will need to add. Do this by first selecting your projects main file in the project navigator pane. Make sure your projects target is selected, and under Build Phases click &#8216;Link Binaries with Libraries&#8217;. Use the + at the bottom of this display and add the <strong>QuartsCore </strong> and <strong>OpenGLES</strong> frameworks.</p>
<p><a href="/2012/09/07/3856/addframework/" rel="attachment wp-att-4107"><img class="aligncenter size-medium wp-image-4107" alt="" src="/wp-content/uploads/2012/09/addFramework-300x135.png" width="300" height="135" /></a></p>
<p>Next, using the &#8216;Add Other&#8217; button, navigate to your downloaded NinevehGL folder and import the <strong>NinevehGL.framework</strong>.</p>
<p><a href="/2012/09/07/3856/addother/" rel="attachment wp-att-4106"><img class="aligncenter size-medium wp-image-4106" alt="" src="/wp-content/uploads/2012/09/addOther-261x300.png" width="261" height="300" /></a></p>
<p>Now onto the code&#8230;&#8230;.import NinevehGL into your header (.h) file,</p>
<div class="wp_syntax">
<pre><span style="color: #993300;">#import</span> &lt;NinevehGL/NinevehGL.h&gt;</pre>
</div>
<p>add the delegate to your @interface, if this is missing your drawview method will never get called.</p>
<div class="wp_syntax">
<pre>@interface ViewController : UIViewController &lt;<span style="color: #333399;">NGLViewDelegate</span>&gt;;</pre>
</div>
<p>In order to see what is being rendered we will need an ivar for an NGLCamera, and for our single object, an NGLMesh. The complete code for all of this should look as follows.</p>
<div class="wp_syntax">
<pre><span style="color: #993300;">#import</span> &lt;UIKit/UIKit.h&gt;
<span style="color: #993300;">#import</span> &lt;NinevehGL/NinevehGL.h&gt; 

@interface ViewController : UIViewController &lt;<span style="color: #333399;">NGLViewDelegate</span>&gt; 
{ 
    <span style="color: #333399;">NGLCamera</span> *_camera; 
    <span style="color: #333399;">NGLMesh</span> *_mesh; 
}</pre>
</div>
<p>In your source (.m) file you must initialize your NGLView, set its delgate to self, define a dictionary with a few basic settings, and initialize the mesh and camera. I am doing this in my viewDidLoad method but depending on your needs, this could be done elsewhere.</p>
<div class="wp_syntax">
<pre>    
- (void)viewDidLoad
{
    [super viewDidLoad];
    <span style="color: #008000;">// Do any additional setup after loading the view, typically from a nib.</span>

    <span style="color: #008000;">// Setup our NGLView.</span>
    <span style="color: #333399;">NGLView</span> *theView = [[<span style="color: #333399;">NGLView</span> alloc] initWithFrame:CGRectMake(40, 40, 240, 360)];

    <span style="color: #008000;">// Set its delegate to self so the drawview method is used.</span>
    theView.delegate = self;

    <span style="color: #008000;">// Add the new view on top of our existing view.</span> 
    [self.view addSubview:theView];

    <span style="color: #008000;">// The content scale factor is used to increase the resolution to take advantage </span></pre>
<pre><span style="color: #008000;"> of retina displays and values range from 1.0 to 2.0. This sets the contentscalefactor </span></pre>
<pre><span style="color: #008000;"> to the max screen scale of the device.</span>
    theView.contentScaleFactor = [[UIScreen mainScreen] scale];

    <span style="color: #008000;">// Setup some initial environment states to be applied to our mesh.</span>
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
	<span style="color: #993300;">kNGLMeshCentralizeYes</span>, <span style="color: #993300;">kNGLMeshKeyCentralize</span>,
	<span style="color: #cc0000;">@"0.3"</span>, <span style="color: #993300;">kNGLMeshKeyNormalize</span>, nil];

    <span style="color: #008000;">// Initialize the mesh which includes the model file to import (.obj or .dae).</span>
    _mesh = [[<span style="color: #333399;">NGLMesh</span> alloc] initWithFile:<span style="color: #cc0000;">@"earth.obj"</span> settings:settings delegate:nil];

    <span style="color: #008000;">// Initialize the camera used to render the scene.</span>
    _camera = [[<span style="color: #333399;">NGLCamera</span> alloc] initWithMeshes:_mesh, nil];

    <span style="color: #008000;">// If a trasparent background of the NGLView is needed</span>
    <span style="color: #008000;">//theView.backgroundColor = [UIColor clearColor];</span>
    <span style="color: #008000;">//nglGlobalColorFormat(NGLColorFormatRGBA);</span>
    <span style="color: #008000;">//nglGlobalFlush();</span>

    <span style="color: #008000;">// The following command displays a 3d view status monitor that will show your current frame rate and number of polygons being rendered in the view.</span>
    [[<span style="color: #333399;">NGLDebug</span> debugMonitor] startWithView:(<span style="color: #333399;">NGLView</span> *)self.view];
}</pre>
</div>
<p>You will need to add at least one method to your source (.m) file, this is the drawView loop. This drawView loop is used to generate each frame being displayed (up to 60 per second). This drawloop is where you would affect the mesh to animate movement or create the effects your a looking to display. The  [_camera drawCamera] is needed to commit the changes and render the frame. The method usually ends with this command.</p>
<div class="wp_syntax">
<pre>-(void)drawView
{
    <span style="color: #008000;">// Rotate on Y axis</span>
    _mesh.rotateY += .5;

    <span style="color: #008000;">// Draw to our camera to display on our view</span>
    [_camera drawCamera];
}</pre>
</div>
<p>In the above example, the _mesh.rotateY += .5 is used to rotate the mesh .5 degrees each time the frame is rendered.</p>
<p>Now build and run the project and you should see a slowly spinning planet Earth. The NGLView was purposely drawn smaller than the background view in order to show how you could overlay this NGLView over any other normal view to add 3D content. If you want the background of the NGLView to be transparent, set the background color of the view to clear and add the following additional commands. There is also a status monitor that can be run to display frame rates and the number of polygons being rendered for optimization.</p>
<p><a href="/2012/09/07/3856/openglviewcapture/" rel="attachment wp-att-4180"><img class="alignleft size-medium wp-image-4180" alt="" src="/wp-content/uploads/2012/09/openGLviewCapture-162x300.png" width="162" height="300" /></a></p>
<div class="wp_syntax">
<pre><span style="color: #008000;">// If a trasparent background of the NGLView is needed</span>
 theView.backgroundColor = [UIColor clearColor];
 nglGlobalColorFormat(<span style="color: #333399;">NGLColorFormatRGBA</span>);
 nglGlobalFlush();

<span style="color: #008000;">// The following command displays a 3d view status monitor that will show your current frame rate and number of polygons being rendered in the view.</span>
 [[<span style="color: #333399;">NGLDebug</span> debugMonitor] startWithView:(<span style="color: #333399;">NGLView</span> *)self.view];</pre>
</div>
<p>There are many commands you can use to affect your object, it&#8217;s movement and how it interacts in it&#8217;s 3D environment, here are just a few basic ones. Advanced animation, movement techniques, object hit testing, custom shaders, etc. would be worthy of a separate tutorial. Enjoy.</p>
<div class="wp_syntax">
<pre><span style="color: #008000;">// rotation</span>
 _mesh.rotateX, rotateY, rotateZ

<span style="color: #008000;">// scaling</span>
 _mesh.scaleX, scaleY, scaleZ 

<span style="color: #008000;">// placement</span>
 _mesh.x,y,z 

<span style="color: #008000;">// offset center of objects rotation</span>
 _mesh.pivot = nglVec3Make(x, y, z)</pre>
</div>
<p><a title="openGLView assets" href="/wp-content/uploads/2012/09/openGLViewAssets.zip">Assets</a></p>
<p><a title="openGLview project file." href="/wp-content/uploads/2012/09/openGLview.zip">Project file</a></p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2012/09/07/3856/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
