Author Archives: adam

What’s New In iOS 8

Apple iOS8 LogoWWDC is upon us, and while hearing about the design of new Trash icon in OS X Yosemite is entertaining, the real substance of the talk for me is the new iOS 8 dev features. While this update isn’t as radical as last year’s iOS 7 update, there is a lot of great new tools coming out that will allow developers to make new and innovative applications. Below you’ll find the highlights from iOS 8 developers page and what they bring to the table. There are a lot of topics, but I’d like to highlight the two most interesting pieces first. Let’s run through the list!

The Top Two

The most dramatic updates to iOS 8 highlighted in today’s announcement are App Extensions and Swift. They are tools that change how developers will go about building applications.

App Extensions – “An app extension (or extension) lets you extend custom functionality and content beyond your app and make it available to users while they’re using other apps”

People will now have ways to make the iOS experience there own. By leveraging Extensions this opens up the platform for users to customize how they would like their operating system to function. While Android has had this to some extent, there users typically weren’t aware of the functionality. Apple is going to put it front and center, and provide a mix and match style that will resonate with consumers.

For App developers, this is going to make interacting with your everyday user much easier! Frequent users of your app don’t have to load up the full application to access the simple parts they interact with the most. We’re going to see an increase in clients wanting extensions built into all their applications in order to increase brand interaction.

Swift – “Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast.”

No one saw this coming. A completely new programing language that can create iOS and Mac applications! While I’m looking forward to reading Apple’s 500 page tutorial on how it works, I have to be a little sceptical as to what its future will be. Apple is making a lot of promises with this, but it could change iOS development from this point on.

For App developers, this tool is going cause a lot of heated discussions in the coming months. I don’t think that this is going to replace Objective-C anytime soon, but it does have real power behind it. In two years time, this has the potential to be the rule, not the exception. The syntax at a glance looks simple to understand, so I think we’re going to see an influx of developers in our community as a result. The lower the barrier for entry language creates the potential for more people to pick it up. Right now the barrier of entry language for Objective-C is high. I know a lot of Javascript developers that wouldn’t touch it, but Swift? They might be ok with the syntax since it will look very familiar. I have the feeling that the iOS world is about to get a huge influx of web developers in the next year because of Swift. We’ll have to give this some time to settle, but it will affect the iOS community for better or worse in the years to come.

Quick Thoughts On Other New Features

There are a bunch of other new features with iOS 8. While not as groundbreaking as the last two topics, they still warrant a quick chat. These features are either upgrades on existing frameworks or Apple implementations of mainstream third party libraries.

HomeKit – Control your home from your phone! This isn’t a new concept and a lot of developers have already implemented this functionality on their own. Nothing too innovative here, but it will bring that functionality into the spotlight. We’re about to see a lot more applications and devices in this space as a result.

CloudKit – The power of the CLOUD! While developers will be happy to see this new option available, I don’t think its going to lead to many innovative ideas.

Manual Camera Controls – This is a welcome update to the AVFoundation library. Having more controls for the camera will make building this functionality in Apps faster and give even more diverse options for the end user.

PhotoKit – Having better ways to access and modify photos on the user’s phone is a great! Working with the camera roll has been a pain in the past, and this hopefully will give an easier way to access that functionality.

Touch ID – While 99% of applications will not need fingerprint identification, it is a cool way to login into an app. It also has the added bonus of feeling like James Bond.

Handoff – Being able to start a process on one device and continue it on another is a nice feature. I can see a lot of application leveraging this, especially universal games. Users will love this and developers will build it. Pure convenience.

HealthKit – There are a lot of health applications out there, and having a central place to aggregate all the data will be a great tool moving forward. For now FitBit and Up, are going to be quite happy. However, I have the feeling that this will become a bigger topic of discussion once we hear more about the new iPhone 6 and possible iWatch.

SceneKit – Game Developers rejoice! You will now have a basic platform to build 3D games. While SpriteKit was a great addition in iOS 7. It didn’t bring much to the table for 3D specific games, this could change that.

SpriteKit – Originally introduced in iOS 7, SpriteKit is getting some quality of life upgrades. I have the feeling this completes the original feature set that Apple wanted to get in last year, but they didn’t have the time to do so. This will make 2D game development even easier and maintainable.

Metal – Games on iOS 8 now have a way to directly access the hardware with Metal. Previously everything was done through OpenGL, but not anymore. Metal is going to allow developers to build amazing looking graphics that are more inline with traditional portable consoles. Expect the Infinity Blade of the next generation device to look amazing.

So That’s iOS 8

Overall, I think Apple is giving some great new tools for developers. From new frameworks to programing languages, there will be a lot of change coming in the next year. While the official iOS release won’t be available until the fall, we can expect some ground breaking new apps on the horizon in 2014.

Specialize?

As a developer, there will be a point in your career when the questions arises… Should I specialize in one area or start to branch out into a new technology? Its an interesting question that leads down the rabbit hole into even more questions. There is no right answer and most of the “correct” answers are situational. So lets take a look at why the question is even being proposed in the first place.

One Job, One Device, One Language

When entering the field as a new developer, more often than not you’ll find a job working with one technology. Most, if not all, the developers I know started out this way. It might be iOS for iPhone, Java for Android, or Web Standards for browsers. The reason you’ll start this way is two fold.

1.) You don’t have enough exposure to programing… yet

2.) Jobs that realistically require more than one technology are rare.

As a new developer, the more you code the more you learn. Every new pattern or method gives you deeper insight into what it means to be a programmer. From here you can slowly begin to understand the craft. Building knowledge in a single language is a much simpler and an easier path than trying to learn two in parallel. Its simply too daunting by comparison. Eventually you’ll come to understand that syntax isn’t as important as the ideas behind them, but this takes time and experience.

As an employer looking for a new developer to add to my team, I want someone well versed in the language my software is in. I want each member of my team to be focused on that technology to ensure that highest quality of code and keep the project under budget. This doesn’t leave much time for cross technology coding.

Personally, I would encourage any starting developer to pick a current technology and learn it through and through. Speaking from my own experience, focusing on one technology will only build the base for learning others faster. As with anything, the more you learn the more experience you’ll have to pull from when investigating something new.

Building Blocks

Technology more than any other industry is constantly evolving. Regardless of how popular a language is today, it won’t be around forever. Talk to someone who has been in the industry more than 10 years, the chances of them saying that all the languages they knew when they first started are still common are slim to none. I’ve been apart of the professional community for 6 years and my first job was building Flash applications. If you asked me today I couldn’t tell you the last time I opened Flash. However I could tell you how to extend a class, write a case statement, or talk about design patterns. That knowledge carries over, and ends up making the building blocks for future technology. The more concepts you understand in a given language, the more you’ll understanding programing.

Keep Learning

Its easy to stick with something you know. Lots of people stick with one technology and go deep. Learning a new methodologies, libraries, and design pattern for that given language. This is great but things that are specific to a given language might not be the best investment of time. Take a second, and look up the Papervision library. If you were a flash developer in 2009, I’m sure you will recall it. If not, this was a popular 3D library at the time for Flash. If you google it now, you’ll find that http://www.papervision3d.org/ is for sale and the community is a ghost town. A lot changes in 5 years, but other times technologies stick around for awhile, just take a look at Java. This is the nature of our industry, but what never changes is hearing about new ideas and the concepts we learn. At the end of the day that is what every programer takes away from their project.

 

The best advice I’ve found is this, regardless of what programming path you choose, keep learning! There isn’t a home in our industry for developers who don’t adapt and grow.  The more exposure to unique programing ideas you have, the faster you’ll understand new ones.

 

Specialize in learning.

iOS Creating a Basic Game

Creating a game can be tough… Most ideas seem simple on the surface, but rarely are. Some of the most difficult, yet rewarding, code I’ve written has come from building games. However, its a tough market to be successful in. There are hundreds if not thousands of mobile games getting released every month. Getting lost in the noise is easy and common. My biggest recommendation is to understand that building a game should be reward enough when first starting out. Even Rovio had 51 unsuccessful titles over the course of 6+ years before creating Angry Birds. The knowledge you gain by the end of a project is be enormous and only make future games better.

In this tutorial we’ll be building a game called “Shields Active”. We will start with the basic goal of the game, expand that into a simplified gameplay document, and finally build the game in SpriteKit.

Shields Active : Basic Goal

Before we start to code, we’ll need a base for our game. Having a simple one liner gives us a solid start. If our statement is longer than one or two sentences its probably too complex. For our game we’ll say :

Prevent objects traveling from one side of the screen to the other by creating other objects for them to collide with.

Now we have our simple goal for the game. This step might seem unnecessary, but the core of the game can be lost very quickly. Even with a base goal, feature creep can overcomplicate and ruin a game. We’re trying to eliminate, the “Wouldn’t it be cool if X happened.” statement. My best advice is to do one thing and then refine it. Once you have that, build upon it.

Shields Active : Game Document

With our base goal in hand we have to expand upon it. Typically we’d create a fully comprehensive game document. This would include everything from user experience to concept art. However we won’t go into that kind of depth. For simplicity sake, we’ll only be writing out basic gameplay outline. This includes things like sprites, sprite actions, user interface, user events and end scenarios.

UI:

– Orientation is landscape locked.

Before Game:

– Button in the center of the screen that says “Start”

During Game:

– Score will be in a label in the top right corner. Text saying “Score x/10”.
– A life meter is in the top left corner. A label saying “Life : 3”.

After Game:

– Label centered reading “You Win!” in a winning scenario or “You’ve Lost” in a loss scenario.
– Button that says “Play Again?”

Sprite Asteroids:

– Create one Asteroid every 1 second.

Sprite Shields:

– Created on Initialization of the game.

User Actions:

– User taps to move the Shields position to the touched location.

Asteroid Action:

– Move across the screen right to left. If they go off the screen, they are removed. The Life total is then decreased by 1.
– Will be generated with a range of speeds.
– If an Asteroid collides with a shield, the Asteroid is destroyed and the shield remains.

End Scenarios:

– If 10 Asteroids collide with the Shield, the game ends in victory. The user will be prompted to play again.
– If life is equal to 0, the game ends in loss. The user will be prompted to play again.

For a simple game that might seem like a lot of information, but each piece is important. When details aren’t written out things can get lost or left to interpretation. Just because you know how something should work, doesn’t mean that will be how a coding partner might understand it. As with any project, being as clear as possible is critical to success. One of the other benefits to settings up a document is that we now have a check list for all the tasks our application needs to accomplish. Lets start coding.

Getting Started

To build this game, we’ll be using iOS Spritekit which was introduced in iOS 7. If you don’t have any experience with Objective-C, don’t worry. This tutorial will take you step by step in building the game, and many of the concepts are transferable to other mobile game platforms.

Lets begin by creating our project. Start up Xcode click File > New > Project > SpriteKit Game. That should bring up the initial setup screen for the project. Name the project “ShieldsActive” and set devices to iPhone.

1_project_setup

Click next, and then a location to save the project. At this point Apple will use its hello world template to start us off. Go ahead and run the project, the result will launch the simulator and you’ll be presented with the SpriteKit Hello World game.

Lets start building our app by locking the orientation to landscape. In the Shields Active project file, uncheck portrait. This leaves us with Landscape left and right checked. This will make our game locked into one mode.

2_orientation

First Steps : Scenes and Transitions

Now that we’ve adjusted the orientation, lets get our game up and running. This is a short list of the next steps.

  • Create a starting scene with some text and a button to start the game.
  • Set the StartScene to be the first one loaded when the application starts.
  • On the StartScene, create the action to load MyScene.

First we’ll make a new landing scene for our game. To add a new class go to File > New > File. In the iOS Cocoa Touch tab, select Objective-C class. Set the name of the file to StartScene and the subclass to SKScene, then create the file. This will add a H and M file for the class. Which stand for “Header” and “Method”, if you want to learn more on why they are called that check out this post. We won’t need to modify the header file for this class, so click on StartScene.m to get started.

3_create_file

You now should be looking at an almost empty file, lets add some code to change that. Add the following code to the project between @implementation and @end lines:


-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue"];
        label.text = @"Shields Active!";
        label.fontSize = 40;
        label.fontColor = [SKColor whiteColor];
        label.position = CGPointMake(self.size.width/2, self.size.height/2);
        [self addChild:label];

        SKSpriteNode *startButton = [SKSpriteNode spriteNodeWithImageNamed:@"Start"];
        startButton.position = CGPointMake(self.size.width/2, self.size.height/2 - startButton.size.height);
        startButton.name = @"StartButton";
        [self addChild: startButton];
    }
    return self;
}

Lets take a look the code. initWithSize is our default constructor, so it is called when the SKScene is initialized. Next we are adding two objects a SKLabelNode and SKSpriteNode to the scene. The SKScene is the canvas for our sprites to be placed on.

The SKLabelNode, as you might have guessed, is a text box for us to display on the screen. We set the properties of that label once the object is created. This includes text, color, font size, and position. Once all the properties are set, we use the addChild method to add the label to our scene.

SKSpriteNode works similarly. You’ll notice that when we create the object, we are passing a long a spriteNodeWithImageNamed of “Start”. This indicates what image the sprite should use based on the ones that have been imported into the project. By setting this variable the object will take on the width and height of the image we are assigning it automatically. However we haven’t added any images into our application yet! Before continuing on lets do that now.

I’ve included a link to the project images here. Download the zip file and unzip it. Locate a folder in your project structure named Images.xcassets, select it . Then highlight all the image assets in the unzipped folder and drag/drop them into the opened Images.xcasset screen. There should already be an AppIcon and LaunchImage in this structure by default. Once placed in this folder, the application will be able to pull in the image files with no fuss.

On a side note, Images.xcassets is new in Xcode 5. Without getting into details, I think its saves a lot of time and effort. You should consider using it in all your future iOS projects when possible.

4_Images_xcasset

Now that we have our SKScene setup, lets set it to the first scene to load when our application starts up. Open the ViewController.m and change

#import “MyScene.h”

to

#import “StartScene.h”

Next inside the viewDidLoad, change the line

SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];

to

SKScene * scene = [StartScene sceneWithSize:skView.bounds.size];

After that, run the application. If everything is setup correctly you should see the following screen in your simulator:

5_shields_active_1

At a glance this looks fine, however there is one more change we need to make in ViewController.m before we’re done. At a glance this screen seems to be fine, however the screen dimensions are off. We’ll need a small update to fix the problem. We’ll need to replace :

viewDidLoad

to

viewWillLayoutSubviews

After making the change, run the application again. You should see a change in the size of the scene and the objects it contains:

6_shields_active_2

When the view is created, it doesn’t take into account if the device’s orientation is in portrait or landscape. Since the default is portrait, and we locked the application to landscape, the device is still using the dimensions of the phone as if it were in portrait orientation. By setting our scene in viewWillLayoutSubviews we know that the orientation change has already happened. This is because the orientation is set further along in stack, before viewWillLayoutSubviews but after viewDidLoad. This results in the correct screen dimensions for our application.

After running the application, you’ll notice that our start button doesn’t do anything. Lets fix that! Go back to StartScene.m, import “MyScene.h” and add the following method below initWithSize:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    //Action for the StartButton Button
    if ([node.name isEqualToString:@"StartButton"]) {
        SKTransition *transition = [SKTransition fadeWithDuration:0.3];
        SKScene * myScene = [[MyScene alloc] initWithSize: self.size];
        [self.view presentScene:myScene transition: transition];
    }
}

This code adds a touch listener to our scene. We detect if a node was clicked with the name of StartButton, which we did in our init method. The name property is how we identify sprites in an event handler. After detecting that our button was touched we create a transition to a new scene, in this case the MyScene class. Transitions are how we go from scene to scene within our game. Creating multiple scenes for different states of the application will keep our code much cleaner and easier to use.

Creating the Game : Shield Sprite

If you run the application, and click the start button you will be taken to the Hello World code we saw earlier. Thats great, but we want to make our own game now! Open up MyScene.m and swap the initWithSize and touchesBegan methods with the following code:

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        self.shield = [SKSpriteNode spriteNodeWithImageNamed:@"Shield"];
        self.shield.position = CGPointMake(self.shield.size.width*2, self.frame.size.height/2);
        [self addChild:self.shield];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) {
       CGPoint location = [touch locationInNode:self];
       self.shield.position = location;
    }
}

Also update the MyScene.h with this code:

#import <SpriteKit/SpriteKit.h>

@interface MyScene : SKScene

@property (nonatomic) SKSpriteNode * shield;

@end

In MyScene.h we are setting our scene to use the Spritekit SKPhysicsContactDelegate, which in basic terms allows us to leverage collision detection and set the gravity of our world. We don’t need it just yet, but we’ll be adding code that requires it soon enough. In the next line we are creating a SKSpriteNode object called shield. We’ll be using shield extensively, so defining it here will accomplish that functionality.

In MyScene.m init method, we define the Shield object we created in the header file. Next, we set its position and add it to the screen. This should be familiar as it is the same way we added a SKSpriteNode in our StartScene class. In our touchesBegan, we are detecting the touch and setting our Shield’s position to the touch location. If you run the application you can see the sprite created and we have the ability to move it around the screen by touching different locations. A good start!

Creating the Game : Adding Asteroids

Now our shield needs something to interact with, so lets add some Asteroids! Replace the update method then create a new method called createAsteroid. Update your project with the following :

-(void)update:(CFTimeInterval)currentTime {
    
    CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
    self.lastUpdateTimeInterval = currentTime;
    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 1) {
        self.lastSpawnTimeInterval = 0;
        [self createAsteroid];
    }
}

-(void)createAsteroid {
    
    SKSpriteNode * asteroid = [SKSpriteNode spriteNodeWithImageNamed:@"Asteroid"];
    
    int minY = asteroid.size.height / 2;
    int maxY = self.frame.size.height - ((asteroid.size.height / 2) + 40);
    int rangeY = maxY - minY;
    int actualY = (arc4random() % rangeY) + minY;
    
    asteroid.position = CGPointMake(self.frame.size.width + asteroid.size.width/2, actualY);
    [self addChild:asteroid];
    
    int minDuration = 1.0;
    int maxDuration = 3.0;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = (arc4random() % rangeDuration) + minDuration;
    
    SKAction * actionMove = [SKAction moveTo:CGPointMake(-asteroid.size.width/2, actualY) duration:actualDuration];
    SKAction * actionMoveDone = [SKAction removeFromParent];
    [asteroid runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}

In MyScene.h under the shield property add :

@property (nonatomic) NSTimeInterval lastSpawnTimeInterval;
@property (nonatomic) NSTimeInterval lastUpdateTimeInterval;

Lots of new code! The update method is called by default and is given the current time. Its also invoked every millisecond. Since we don’t have control over how often its called we have to build in our own way of keeping track. In this code we are setting up CFTimeInterval to keep track of how long in between updates. This allows us to control how much time has passed before calling the createAsteroid method. We’re setting lastSpawnTimeInterval > 1 so that the method is called every 1 second. If we increase to 3, it would be every 3 seconds.

Now take a look at createAsteroid. First we create an asteroid SKSpriteNode and set the position to be beyond the view of the screen with a random Y value. This should seem similar to how we created the shield.

According to our gameplay outline the asteroid has to move across the screen from right to left, to do this we’ll need a runAction. This will take in an array of SKActions to be executed in sequence. For our purpose we’ll have two, actionMove and actionMoveDone. actionMove takes our asteroids current position and has it move on the X axis to the left till it goes slightly off screen. Once it reaches its destination we call actionMoveDone, which removes the sprite from the screen. This is to keep our environment clean and keep memory in check. Run the projects to see asteroids flying across the screen!

7_shields_active_3

So far so good! But our the asteroids go right through the shield. Lets make our shield pull its weight and block those asteroids. To do this, we’ll need to add collision detection. Lets add some code to our MyScene.m :

At the top of the page, between @implementation and initWithSize add :

static const uint32_t shieldCategory =  0x1 << 0;
static const uint32_t asteroidCategory =  0x1 << 1;

In the init method below [self addChild:self.shield] add:

self.shield.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.shield.size];
self.shield.physicsBody.categoryBitMask = shieldCategory;
self.shield.physicsBody.contactTestBitMask = asteroidCategory;
self.shield.physicsBody.collisionBitMask = 0;
        
self.physicsWorld.gravity = CGVectorMake(0,0);
self.physicsWorld.contactDelegate = self;

At the bottom of createAsteroid add:

asteroid.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:asteroid.size];
asteroid.physicsBody.categoryBitMask = asteroidCategory;
asteroid.physicsBody.contactTestBitMask = shieldCategory;
asteroid.physicsBody.collisionBitMask = 0;

Then add the following methods at the bottom of the class:

- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;
    
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    } else {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }
    
    if ((firstBody.categoryBitMask & shieldCategory) != 0 && (secondBody.categoryBitMask & asteroidCategory) != 0){
        [self shield:(SKSpriteNode *) firstBody.node didCollideWithasteroid:(SKSpriteNode *) secondBody.node];
    }
}

- (void)shield:(SKSpriteNode *)shield didCollideWithasteroid:(SKSpriteNode *)asteroid {
    [asteroid removeFromParent];
 }

Once the code has been added, run the project. Now our asteroids are removed when they collide with a shield. Perfect! Lets walk through the code we added. If you take a look at init and createAsteriod you’ll notice the some similarity in the code around “physicsBody”. In this area we are setting the objects to have physics bodies. Without that the objects won’t be able to detect collisions in our didBeginContact method. You’ll notice that we set two “static const uint32_t “ variables at the top of the application. This globally establishes the two types of objects when we get into the collision detection method.

Next we have to set the global gravity of our scene. We are setting it to be 0, otherwise by default SpriteKit will apply earth like gravity to objects with physicsBody. Try removing the lines from our init, run the application and see what happens:

self.physicsWorld.gravity = CGVectorMake(0,0);
self.physicsWorld.contactDelegate = self;

You’ll notice how all our sprite now drop off the screen. This is important in many games, but for ours we’ll want to stick with no gravity so add that code back in.

Since our sprite objects now interact with each other, we need to detect when they collide. By default Spritekit will call a didBeginContact method if any physicsBody object collides with another. Our game logic only cares about Shield to Asteroid collisions, not Asteroid to Asteroid, so we’ll have to code that ourselves. Take a look at didBeginContact, we detect the two bodies and compare them to check for the collision of an asteroid and shield. If true we call our shield did collide with asteroid method, which removes the asteroid sprite.

Setting up UI

Our game is coming along nicely, but we have no way of telling if we’re winning or losing! Lets add some basic UI elements to keep track of our win or lose case. Update the MyScene.h file with the following properties:

@property (nonatomic) SKLabelNode * scoreLabel;
@property (nonatomic) SKLabelNode * lifeLabel;
@property (nonatomic) int Life;
@property (nonatomic) int Score;

Within the MyScene.m we’ll be making some changes as well. In init we’ll be adding a call to the init UI method. This can be placed below where we set our gravity code.

[self createUI];

Next we’ll need to add this method :

-(void)createUI {
    
    self.Score = 0;
    self.scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue"];
    self.scoreLabel.fontSize = 15;
    self.scoreLabel.fontColor = [SKColor whiteColor];
    self.scoreLabel.text = [NSString stringWithFormat:@"Score: %d / 10", self.Score];
    self.scoreLabel.position = CGPointMake(self.size.width - self.scoreLabel.frame.size.width/2 - 40, self.size.height - (40 + self.scoreLabel.frame.size.height/2));
    [self addChild:self.scoreLabel];
    
    self.Life = 3;
    self.lifeLabel = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue"];
    self.lifeLabel.fontSize = 15;
    self.lifeLabel.fontColor = [SKColor whiteColor];
    self.lifeLabel.text = [NSString stringWithFormat:@"Life: %d", self.Life];
    self.lifeLabel.position = CGPointMake(self.lifeLabel.frame.size.width/2 + 40, self.size.height - (40 + self.lifeLabel.frame.size.height/2));
    [self addChild:self.lifeLabel];
}

This will provide us with some SKLabels of basic information, but we need to update them when something happens! Lets make some modifications to the createAsteroid and shielddidCollideWithasteroid:

In createAsteroid replace :

[asteroid runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];

with

SKAction * loseAction = [SKAction runBlock:^{
        self.Life -= 1;
        self.lifeLabel.text = [NSString stringWithFormat:@"Life: %d", self.Life];
}];
[asteroid runAction:[SKAction sequence:@[actionMove, loseAction, actionMoveDone]]];

In shielddidCollideWithasteroid below [asteroid removeFromParent]; add:

self.Score += 1;
self.scoreLabel.text = [NSString stringWithFormat:@"Score: %d / 10", self.Score];

In createAsteroid we add another SKAction to help us update the Life when an asteroid goes off the screen. Similarly in shielddidCollideWithasteroid, we modify the text of Score to reflect when an asteroid is destroyed. Run the application and you’ll see the following.

8_shields_active_4

Adding Win and Loss Conditions

Our game can keep track of Life and Score, but we don’t have any win or lose conditions yet. To do this we’ll be making some modifications to MyScene.m and creating a new scene class ‘EndScene’. The EndScene will handle either case, and allow our users to play again. Clean and simple!

Start by adding the following to the top of the MyScene.m :

#import "EndScene.h"

Next in createAsteroid replace the loseAction block with the following:

SKAction * loseAction = [SKAction runBlock:^{
        self.Life -= 1;
        self.lifeLabel.text = [NSString stringWithFormat:@"Life: %d", self.Life];
        if (self.Life == 0) {
            SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
            SKScene * gameOverScene = [[EndScene alloc] initWithSize:self.size userHasWon:NO];
            [self.view presentScene:gameOverScene transition: reveal];
        }
}];

Next in shielddidCollideWithasteroid add the following to the bottom part of the method:

if (self.Score >= 10) {
        SKTransition *transition = [SKTransition fadeWithDuration:0.3];
        SKScene * gameOverScene = [[EndScene alloc] initWithSize:self.size userHasWon:YES];
        [self.view presentScene:gameOverScene transition: transition];
}

This will set our lose condition to fire if life goes below 1 and our win condition to fire if Score is 10 or greater. In those events, we are calling a transition to a new scene, just like we did back in StartScene.m at the beginning of the project. The only difference is that we are calling initWithSize with an additional parameter of userHasWon. In this case we are overloading the native init function of that scene. This allows us to pass the key data we need to setup the screen correctly. In our case, if a user won or lost. Lets create a new SKScene, just like we did earlier but this time with the name EndScene.

In our EndScene.h :

@interface EndScene : SKScene

-(id)initWithSize:(CGSize)size userHasWon:(BOOL)userHasWon;

@end

In our EndScene.m :

#import "EndScene.h"
#import "MyScene.h"

@implementation EndScene

-(id)initWithSize:(CGSize)size userHasWon:(BOOL)userHasWon {

    if (self = [super initWithSize:size]) {
        
        NSString * gameEndText;
        if (userHasWon) {
            gameEndText = @"You Win!";
        } else {
            gameEndText = @"You’ve Lost.";
        }
        
        SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue"];
        label.text = gameEndText;
        label.fontSize = 40;
        label.fontColor = [SKColor whiteColor];
        label.position = CGPointMake(self.size.width/2, self.size.height/2);
        [self addChild:label];
        
        SKSpriteNode *playAgain = [SKSpriteNode spriteNodeWithImageNamed:@"PlayAgain"];
        playAgain.position = CGPointMake(self.size.width/2, self.size.height/2 - playAgain.size.height);
        playAgain.name = @"playAgain";
        [self addChild: playAgain];
        
        
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];
    
    //Action for the playAgain Button
    if ([node.name isEqualToString:@"playAgain"]) {
        SKTransition *transition = [SKTransition fadeWithDuration:0.3];
        SKScene * myScene = [[MyScene alloc] initWithSize: self.size];
        [self.view presentScene:myScene transition: transition];
    }
    
}
@end

This code should all seem very familiar as it is almost identical to StartScene. The major difference being the name of our button and the addition of gameEndText which sets the correct text for the label based on the boolean value that was passed along in the init function. The play again button, allows us to go back to the MyScene which will restart the init causing the game to start over again. Now we have a complete game!
9_shields_active_5

Summary

You’ve done it! At this point you should have a basic game with a start screen, game play, and end screen. It might seem basic, but these building blocks can lead to bigger and better games. I hope you’ve gained a better understanding of SpriteKit from this tutorial and go build your own games!

The final source code for the finished project can be found on my github page.

https://github.com/ajacaruso/ShieldsActive

CSS : Percent Layouts

Why Percentages?

Over the course of the last four years, I’ve gained a lot of respect for percent-based layouts. They provide a high level of flexibility while maintaining cross device / cross-browser cohesiveness. The main goal of a percent layout is to eliminate static pixel values from your code whenever possible and replace those static numbers with percentages. It’s easier said than done, but the finished product tends to be much stronger.

From a developer perspective, it’s a change of pace from what you might be used to. A lot of teams focus on the idea of “Pixel Perfect”, meaning using hard values for width and height of all elements. I like to focus on Percent Perfect.. You can still build a site using percents and have it match comps, but ultimately this works best with collaboration between design and development. Creating designs built in this way can go a long way in saving time down the line when deploying to different sized devices. Most likely this approach will be used for mobile / tablet styling with media queries to change percentages values to favor traditional the desktop design and user experience.

Coding Basics

For a new web standards developer, understanding the overall concepts of width and height percentages can be a bit daunting. The most important thing to keep in mind while using percentages is to keep track of your math and have a good understanding of your intended layout.

Let’s get started with a simple example and work our way up. Below will be our HTML source throughout the examples. We’ll only be modifying the CSS from here.

<h1 id="site-title">Main Title</h1>
<section id="container-info">
<h1>Info Title</h1>
   <div>
      <p>Info paragraph</p>
      <a href="”http://blog.adamjacaruso.com”">Info Link</a>
   </div>
</section>

Let’s start with the basic rule that governs how all your percentages function. The percentage value of an element is based on its parent’s set value. At its essence, your percentages are based on the container of your object, NOT the page itself (unless the container happens to be the body). If we apply some css to the above HTML, we can see this in action:


#site-title{
background-color: #ff0000;
width: 30%;
}

#container-info{
background-color: #00ff00;
width: 60%;
}

#container-info h1{
background-color: #0000ff;
width: 50%;
}

jsfiddle Example 1

percents_example1

The CSS sets the #site-title element to 30% and the #container-info to 60%. Since they have no parent-level elements with a defined width, they are relative to the document’s width. The document’s width is dynamic and relative the dimensions of the browser window. Within #container-info we set the h1 tag to 50%. Its parent level element is #container-info, so its width is 50% of that element. In the context of the document width, it’s 50% of 60%, which is 30%; the same as our #site-title.

The math behind the above code shouldn’t be too surprising, 0.6 * 0.5 = 0.3.

What about height?

While height can use percents as well, its default value isn’t what you might expect. If we take our width example css and change it to height, you might expect the inverse. Lets try it.

#site-title{
background-color: #ff0000;
height: 30%;
}

#container-info{
background-color: #00ff00;
height: 60%;
}

#container-info h1{
background-color: #0000ff;
height: 50%;
}

percents_example2

As you can see, its a big pile of nothing. Height still follows the same rules that apply to width, so you might ask why is it not rendering as the height of the browser? In our example, the top level parent is the body tag. Everything styled should be a child of that element. The body tag’s width is relative to the window size and height is, by default, defined by its content. Without a defined value, percentages don’t work. For height we have to have a defined value for our percentage to be based on. So if we apply this to our example, we can see how it works.

#site-title{
background-color: #ff0000;
width: 30%;
height:50%;
}

#container-info{
background-color: #00ff00;
width: 60%;
height: 300px;
}

#container-info h1{
background-color: #0000ff;
width: 50%;
height: 50%;
}

jsfiddle Example 3

percents_example3

For #site-title, we’ve set the height to be 50%. Since our body doesn’t have a defined height, it’s basically a worthless line of code. If we look at #container-info, we’ve set its height to be 300px. Now, its children will have a real value to work with. To see height percentages working as expected, we’ll set #container-info h1 to 50% height. With its parent having a height of 300px, 50% of that sets the element to a height of 150px.

I’ll admit, height percentages are not used often. However, combined with media queries, it can be very helpful. You now only would have to change the parent pixel value in one query and all your corresponding percentage heights will scale! A very valuable piece of information, but we’ll save media queries for another post.

Odds and Ends :

With those basics on height and width, you can start to build out virtually any layout. I won’t go through all the ways you might have to position your elements using percentages, but I’ll provide a few examples of styling that might be helpful. We’ll be walking through the following CSS:

#site-title{
background-color: #ff0000;
width: 90%;
text-align: center;
margin: 0 auto;
}

#container-info{
background-color: #00ff00;
width: 90%;
margin: 0 auto;
}

#container-info h1{
background-color: #0000ff;
}

#container-info div{
overflow: auto;
}

#container-info p{
width:50%;
color: #fff;
background-color: #000;
float:left;
}

#container-info a{
width:40%;
margin: 0 5%;
color: #fff;
background-color: #333;
float:right;
}

jsfiddle Example 4

percents_example4

There are a few basic things that we’ll extract from this CSS that percentages want to leverage.

Centering: Its not much different than how you would center an element normally. Just apply margin: 0 auto; like we would normally to a block element. Most mobile designs will have a balanced gutter on both sides. The best way to accomplish this is to set the element’s width to an even number, in our example #container-info has a width of 90% with the margin set to auto. Now all the content in the parent container is centered with some spacing of 5% on each side.

Sections: With percentages, we can create sections within our parent element to break up content. If we look at #container-info, we see that we’ve set the container to have overflow: auto. This allows us to create elements inside that container, and apply the float value, while having the #container-info element not lose its height. Once that’s set, we can float our p tag left and a tag right. With the widths set to numbers adding up to 90%, we have them fit perfectly inside the container. This is very useful in layout design to have your elements expand and contract with the screen size’s width.

Percent Margin: Creating margins with percents allow for spacing between elements that scale with your design. In our example, #container-info a has a width of 40% and a margin-left / margin-right of 5% with our p tag at 50%. Total that’s 5+5+40+50= 100% of the container width, a perfect fit. Keep in mind, this also works for padding as well, and it will also add the total width.

Percents are an important part of web development, making your site tight and responsive. It may feel daunting at first, but once you understand the basics the time you will save in pixel pushing and restructuring is well worth the time invested.

iOS Scrabble Word Detection

A few months back I was working on a prototype for a word game. Part of that game was writing a word detection algorithm. Most games handle this by creating a local database of all the word their game accepts. That way they can cross reference the word and control what their game considers acceptable. Getting that list however isn’t a simple task. Since the game was in beta, I decided to leverage the native dictionary for my detection. Also not a simple task but quicker to implement.

To start we need to have our function detect if a word is valid.

-(bool)isRealWord:(NSString *)currentWord{
    
    bool isValid = false;
    
    UITextChecker* checker = [[UITextChecker alloc] init];
    NSRange range;
    
    range = [checker rangeOfMisspelledWordInString:currentWord range:NSMakeRange(0, [currentWord length]) startingAt:0 wrap:NO language:@"en_US"];
    
    if (range.location == NSNotFound) {
        isValid = true; 
    }
    return isValid;
}

The core of the functionality is on the highlighted line, which sets the range for misspelling. The easiest way to detect if a word is real is to cross check for misspellings. By checking the word against this we know that the word is a real word. A fairly simple check that gets us the first part of the information we require to detect a word.

The second part of the equation is to know if the word is a valid scrabble word. For example, a persons name is not a word. This gets a bit more complex, since some words have multiple meetings. The solution to this, at its core, is to use the word in a sentence and detect what type of word it is.

-(bool)isAllowedWordType:(NSString *)currentWord{
    
    __block bool isAllowedWordTypeValid = true;
    NSString * currentWordUpperCaseFirstLetter =  [currentWord stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[currentWord substringToIndex:1] uppercaseString]];
    
    NSString *str = [NSString stringWithFormat: @"the %@ is ", currentWordUpperCaseFirstLetter];
    
    NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:[NSArray arrayWithObject:NSLinguisticTagSchemeNameTypeOrLexicalClass] options:~NSLinguisticTaggerOmitWords];
    
    [tagger setString:str];
    
    [tagger enumerateTagsInRange:NSMakeRange(0, [str length]) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:~NSLinguisticTaggerOmitWords usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
        
        if([tag isEqualToString:@"OtherWord"] || [tag isEqualToString:@"PersonalName"])   {
            isAllowedWordTypeValid = false;
        }
        
    }];
    
    return isAllowedWordTypeValid;
}

First we set the word to have a capitol letter as the first character of the word. This is important in the detection of the difference later in the function for “PersonalName”. We then put that word in the string “the (word) is”. This sentence fragment puts context around what we are trying to detect to help our code better understand the scrabble logic around playable words. We then create a NSLinguisticsTagger and set the String we created. The code then analysis that string to extract the type of tag that is associated with our word. There are many different types of tags, however for our scrabble word detection, we’re primarily interested in “OtherWord” and “PersonalName” as these are the failure points for the sentence.

When we apply these two functions together we can determine if a word is valid. It took some time to figure out this method of detection, but its still a lot less time then building and managing a database. I still recommend the database solution to ensure perfection, however if you’re looking to make a quick proof of concept this is a great start.

You can find a working example of this approach on my Github. Word Detection Example Project Happy prototyping!

Global Font Scaling with Media Queries

Utilizing percentage fonts, and percentages overall, allows for more flexibility when writing responsive websites. It might be easy enough to change the pixel values for each element in your media queries that requires it, but the work is already done when you implement percentages so why not leverage it? Percentages get their value from the closest parent element which has the same key value defined.

<div>
	<h1>100%</h1>
	<h2>150%</h2>
</div>
div { font-size: 12px; }
h1 { font-size: 100% }
h2 { font-size: 150% }

The example shows how defining the parent value at 12px seeps down into its children’s percentage value. The h1 is 100% of 12, so it has the same font-size of 12 pixels. However the h2 element has a font-size of 150%, as a result its pixel value renders as 18 pixels. Using this we can scale all the font values of a page off one base value. Knowing that, we can modify just the base to increase proportionately all the fonts inside our page. This is where media queries make things like dynamic font size quick and easy. By just changing the base, all the percentages get updated with minimal code.

@media all and (min-width: 800px) {
    div{ font-size:18px; }
}

In this example our base value would increase and all the percentage fonts would dynamically update. Going from a base of 12px to 18px.

Percentages moves responsive design forward, so its important to understand its concepts as it becomes more common place. Its concepts are basic and used correctly can lead to well crafted and thought out web standards applications.

Android Studio, First Impressions

Android StudioIts been a few weeks since itscome out, but I wanted to take some time and talk about Android Studio. Android developers have wanted this for a long time. Honestly this IDE has been long overdue . Most Android developers, or at least from what I’ve experienced, use Eclipse. While it gets the job done, something has to be said for having an IDE that is truly focused and refined to what you’re developing.

The most direct comparison of the path Google wants to go down is how Apple positioned xCode. An IDE created by Apple for developing Mac and iOS applications. Sounds like a solid plan to me, and it must make sense to Google as well since they are doing the same thing with Android Studio. With tons of new hardware coming in all shapes and sizes, Android needs a better IDE to manage the demands of the market.

Android Studio seems to be the answer we’ve been waiting for, but does it solve the primary issues plaguing the growth of Android development? Lets see…

How Easy is it to Get Started as a New Developer?

Regardless of the platform starting to develop for a new platform can be intimidating, Android is no exception. Currently setting up Eclipse with the SDK is the prefered method among the development community. While Google’s SDK download now includes Eclipse, with the SDK already installed, it still requires a working knowledge of Eclipse get everything setup properly for development and maintaining that environment. Android Studio rolls everything into one install, including the SDK. Also it will prompt when updates are available and automatically setup your environment. Overall I think its much easier to get started with Android Studio.

Practicality of Testing Multiple Devices?

android-studio-device previewOne of the biggest issues with Android is viewing your work across multipledevices. Android Studio attempts to address this issue by showing multiple previews of your layouts. While this is a nice step forward, its still far from being optimal. Currently you can view the devices in preview mode when building the XML layout file, but thats the extent of the functionality. Unfortunately there still is not a solid way to test your application across multiple devices optimally without 3rd party software. This leads to something we aren’t getting, a better simulator. Its true that the Android Simulators have gotten better, but the physical device is still significantly faster. I wasn’t expecting this with Android Studio, but would have been a great nice to have.

Easy to use with version control? (Git/SVN)

Probably oneof the strongest features of Android Studio is their integration with Git and SVN. Personally all my projects are managed through Git, and having it built into the IDE has been great. I’ve been using the EGit plugin for Eclipse for some time now, but having Git built into the core of the IDE makes for a better experience.

Interface problems?

This is one of the biggest disappointments of Android Studio. Google had the opportunity to create an brand new IDE with a simple and elegant interface, instead we got a reskinned Eclipse. Most of the functionality and buttons do what you would think, but once in awhile it can become hard to find where you need to go. For example, I have a thread on Stack Overflow with, as of now, 9 upvotes based on where you go to change what the default device for a project. Its kept in a odd place and it defaults to simulator instead of the online device, something that should be opposite. I think they’llhave to put in some quality of life changes to the UI before they hit 1.0 so it can be more user friendly and intuitive.

Is it Stable?

I’ll start this section off with a quote from Google.

“Caution: Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs.”

In my opinion its fairly stable. I’ve had the application crash a few times, but nothing more or less than the frequency of Eclipse. Also keep in mind this is still in preview, so there are bound to be issues. As new features get added and bugs get fixed the quality of the application can only get better.

Quick Summary

Android Studio has a lot of positives and in a few years time will be the default IDE for most Android developers. Its feature set is vast and more things are being added every month that make it better and better. That said, I foresee adoption being slow. Right now Android Studio is still in its early beta stages, and will need a 1.0 before it starts being accepted in the mainstream. For new developers, It might be worth starting to use this build now before learning eclipse. Both have caveats, and if this is the future, its worth learning now if you’re fresh. For current developers, I’d stick with Eclipse for now but be aware of this IDE and know that down the line you’ll more than likely need to make the switch.

 

Starting Up

Hey all, after a recent hiatus I’ve decided to restart the site from the ground up. I still plan on posting about new technology and projects, but I’ve also decided to add some coding tutorials and code snippets that I’ve found to be helpful. Hopefully you enjoy reading and learning from my posts!