Tapity Tapper (My iOS Flappy Bird Clone using Sprite Kit): Applying Impulse

Taking off where we left off, we are going to continue by adding a box, so our red rectangle doesn’t fall off the screen, and then we are going to modify the touchesBegan method so instead of spawning a lot of red rectangles, it will apply impulse to a single one.

We achieve our first task with only one line of code (isn’t Sprite Kit great or what?). We add that line to our initWithSize method, and now it should be looking like this:

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */

self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, self.size.width, self.size.height)];
}
return self;
}

What we are doing here is initializing the physics body of our scene, the bodyWithEdgeLoopFromRect, creates an edge that has no volume or mass, described by the rectangle given (in this case we are using the complete size of the scene), that is not dynamic, which means it won’t be simulated (moved) by the physics engine.

If we run the project in the simulator or on our device, we can see that our red rectangles no longer fall off the screen, and we can appreciate better the interactions between them that the physics engine is simulating for us.

Red rectangles

 

Next we are going to change our touchesBegan method, but first, we are going to make our red rectangle a property. For that we are going to declare an interface just below the import of our .h and the implementation tag.

#import "JCMyScene.h"

@interface JCMyScene(){}

@property SKSpriteNode *rectangle;

@end

@implementation JCMyScene

And now we change our touchesBegan method like this:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    //is rectangle different from nil
    if (!self.rectangle) {
        //get a single touch
        UITouch *touch = [touches anyObject];
        //get the location of the touch
        CGPoint location = [touch locationInNode:self];
        self.rectangle = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:CGSizeMake(50, 50)];
        //set the newly created node position to the position of the touch
        self.rectangle.position = location;
        //initialize the physicsBody with the size of the rectangle
        self.rectangle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.rectangle.size];
        //gravity is going to be simulated on this node
        self.rectangle.physicsBody.affectedByGravity = YES;
        //adding the node to the scene
        [self addChild:self.rectangle];
    }

}

We first check if the property rectangle is different from nil, if it is, we initialize it and add it to the scene. If you run it now, the first time you tap the screen a single red rectangle will appear and “fall” to the ground, and then nothing will happen no matter how much you tap the screen.

And the last thing we are going to do this time, is to apply impulse to the red rectangle if we already have a red rectangle initialized. We are also adding a line to set the mass of our rectangle to 0.5.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    //is rectangle different from nil
    if (!self.rectangle) {
        //get a single touch
        UITouch *touch = [touches anyObject];
        //get the location of the touch
        CGPoint location = [touch locationInNode:self];
        self.rectangle = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:CGSizeMake(50, 50)];
        //set the newly created node position to the position of the touch
        self.rectangle.position = location;
        //initialize the physicsBody with the size of the rectangle
        self.rectangle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.rectangle.size];
        //gravity is going to be simulated on this node
        self.rectangle.physicsBody.affectedByGravity = YES;
        self.rectangle.physicsBody.mass = 0.5f;
        //adding the node to the scene
        [self addChild:self.rectangle];
    }
    else{
        [self.rectangle.physicsBody applyImpulse:CGVectorMake(0.0f, 250.0f)];
    }

}

As you can see, the impulse is one line of code only. The impulse parameter must be a vector, in this case, is positive in the y axis. So our red rectangle is going to “jump”.

Go ahead and run the code. This is it for now, remember that you can also check the code we did on this post on GitHub.

Tapity Tapper (My iOS Flappy Bird Clone using Sprite Kit): Getting Started

Flappy Bird is a fairly simple game, you tap the screen to keep a bird flying, trying to avoid an endless parade of obstacles, and if you touch one, you die. Every time you avoid touching an obstacle you are awarded by one point, the objective of the game?, try to win as much points as you can.

What do we need in order to clone it?

  • Gravity: We all know what happens when you don’t tap the screen, the little bird just falls to the ground and dies.
  • Spawning Scrolling Obstacles: The obstacles keep coming from one side of the screen endlessly, at least until you die, which takes us to the next point.
  • Collision Detection: We must be able to tell when the bird touches one of the obstacles, because that is game over.
  • User Input: The user taps the screen to apply impulse to the bird.

All of this stuff is used in a lot of games, and there are a lot of game engines that facilitate the mentioned tasks. Let’s get our hands dirty.

Fire up Xcode, create a new iOS SpriteKit Game project, name it wherever you want, and make it universal.

Creating a Sprite Kit Project

Next we are going to change the properties of our project, to set the device orientation to only Portrait.

setting Device Orientation So the Xcode was nice enough to initialize our project.

Go ahead to  [your prefix]MyScene.m which, in my case is JCMyScene.m and in the (id)initWithSize:(CGSize)size method delete everything after the setting of the background color. You should have something like:

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

    }
    return self;
}

We are going to play with gravity.

Sprite Kit has an integrated physics engine,  that simulates physics on the objects we have on the screen. By the way, what we see on the screen is called scene, and the objects we have on the scene are called nodes.

Now we are going to modify the touchesBegan, so every time we touch the screen, we are going to add a node to the scene, in this case, a red rectangle. We are going to initialize its physics body, tell it to be affected by gravity, and we are going to watch it fall down the screen.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        //get the location of the touch
        CGPoint location = [touch locationInNode:self];

        SKSpriteNode *rectangle = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:CGSizeMake(50, 50)];
        //set the newly created node position to the position of the touch
        rectangle.position = location;
        //initialize the physicsBody with the size of the rectangle
        rectangle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:rectangle.size];
        //gravity is going to be simulated on this node
        rectangle.physicsBody.affectedByGravity = YES;
        //adding the node to the scene
        [self addChild:rectangle];

    }
}

It’s as simple as that, in fact, if you run the code on the simulator (or on your device if you are in the iOS developers program), and you spawn several red rectangles, you are going to notice that  if they touch, they are going to interact, the physics engine of Sprite Kit, simulates all that for us.

rectangle Falling

in addition to the affectedByGravity property, there are several others properties of the physics bodies that we can manipulate to make the interactions more interesting and accurate:

  • mass
  • density
  • area
  • friction
  • restitution
  • linearDamping
  • angularDamping

You can check out the documentation of the SKPhysicsBody class reference to learn more, and you can check the code of this post  here.

We are going to continue on the next post.

Tapity Tapper: My Flappy Bird Clone using SpriteKit

Tapity Tapper

I know. I know, I know…

So today, I made a Flappy Bird clone. I will upload the complete code to GitHub, and the next posts in this blog are going to be in the form of a tutorial.

There must be many many Flappy Bird clones tutorials already out, I guess, I haven’t really look into it,  but hey, let me show you mine.

You are officially warned.

Barack Obama wants you to learn to code.

So if you haven’t seen it, here’s the president of the United States of America asking his citizens to learn to code:

This is part of a campaign to get people to code.

In case you didn’t know it already, being a programmer is awesome, and this is the best time to be a programmer.

Learn to code from your living room, in whatever country you are, in Harvard,  or learn a programming language the hard way. I mean do that, but only if you like programming, don’t do it for the money, do it for the love of it.

 

This post is not about programming at all (or maybe)

Invictus by William Ernest Henley

Out of the night that covers me,
Black as the pit from pole to pole,
I thank whatever gods may be
For my unconquerable soul.

In the fell clutch of circumstance
I have not winced nor cried aloud.
Under the bludgeonings of chance
My head is bloody, but unbowed.

Beyond this place of wrath and tears
Looms but the horror of the shade,
And yet the menace of the years
Finds and shall find me unafraid.

It matters not how strait the gate,
How charged with punishments the scroll,
I am the master of my fate:
I am the captain of my soul.

I love that poem and I read it thanks to ZEN PENCILSI highly recommend surfing that page, the dude is awesome, that poem and other poems/quotes he illustrates help me to find my motivation.

 

The SUDO Principle, the Flappy Bird and WhatsApp

SUDO Principle

  • Start where you are.
  • Use what you have.
  • Do what you can.

That’s it. Excellent advice for people wanting to do a software project, and not knowing where to begin. Just start now, use whatever resources you have, and do what you can.

It’s actually a quote from Arthur Ashe, a former world number 1 professional tennis player.

About the birds and the bees err WhatsApp

Today is the best day to be a developer.

Do you need evidence?.

  • Flappy Bird: let’s just said that the guy developed the game in about three days, and was winning about 50k a day.
  • WhatsApp: a startup of 55 employees that is worth more than United Continental, American Airlines, Ralph Lauren, Marriot International, Campbell Soup, Coach, and Tyson Foods. Bought by Facebook for $19 billions.
  • Also, Facebook, and of course there are other examples.
  • There’s also the fact that software engineer was the best job in 2012.

Have you heard about William Kamkwamba, the dude made a windmill that powered a few electric appliances, with with stuff he collected from a local scrapyard, with the knowledge he obtained reading books, from a public library, in a language he didnt’t understand!. He wanted to finish school but his family was too poor to pay for the school tuition. Did I mention that he was 14 years old when he built that?.

So this awesome, awesome dude, had to do all those things in order to created something great.

We programmers only need a computer and an internet connection. So, what are we waiting for?.

JCInput: Now with images

For past posts about JCInput go to:

It’s been almost five months since I last did some changes to JCInput, but now you can use images for the joystick.

joystick image

How beautiful is that? (not so much really…)

Using it is easy:

        imageJoystick = [[JCImageJoystick alloc]initWithJoystickImage:(@"redStick.png") baseImage:@"stickbase.png"];
        [imageJoystick setPosition:CGPointMake(80, 200)];
        [self addChild:imageJoystick];

Next step, image buttons, and of course fixing the turbo button, that sometimes keeps firing.

So, if you find yourself in the need for a joystick and buttons for your iOS game, why not JCInput?.