brandontreb.com Tips And Resources For Software Consultants

Cocos2D Tutorial – Dynamically Coloring Sprites

Custom Bitizens

Have you ever seen a game (such as Tiny Tower) that contains similar sprites that only vary by certain attributes (coloring, shading, accessories, etc…)? I would often wonder how long it would take the artists to create each permutation of these sprites. After discovering that you can call a method on a CCSprite called setColor, I realized how most of this customization is done in code.

This tutorial will be a continuation of my last post about creating your own Bitizen in Photoshop. So, if you don’t already have a Bitizen character to work with, I suggest you follow that tutorial OR download my template here.

White Out

As I mentioned above, we are going to be using the setColor method of CCSprite to dynamically color each part of our Bitizen. The way it works is each pixel’s color is multiplied by the value passed into setColor giving it a “tint”. So, pixels that are all white will be fully tinted and pixels that are all black will have no change.

So, our first goal is to create an “all white” version of our Bitizen. Don’t worry about shading for now, I will cover that in a moment. I just started with our Bitizen as a base and created new layers for each of the “white” components.

You should end up with 5 new layers:

  • white-head
  • white-skin
  • white-hair
  • white-pants
  • white-shoes

For each layer, trace over the corresponding colored layer. For the “white-skin” layer, make sure to trace over the hands as well as the face. This will ensure that your Bitizen’s color is consistent. When you are done, your Bitizen should look something like this:

White Bitizen

Looks pretty bland… The next step is to add our shading. We will be using only black with varying alpha in order to achieve the desired shading. So, make sure to play with it a bit and get the shading to your liking. Add a new shading layer for each component (or simply draw on top of the current layer with the black pencil).

Your bitizen should look something like this after doing all of the shading:

Shaded Bitzen

Chop It Up

The final thing we need to do with our graphic is chop up the pieces so that they can be individually colored. Convert each of the white-* layers to Smart Objects, copy them to a new document, and save them. You should end up with 5 .png files (head.png,skin.png,hair.png,pants.png,shoes.png).

I increased the size of my Bitizen by 4 before doing this step. You might consider increasing their size as well. Remember that the size increase you choose will change some of the values when we recreate the Bitizen in Cocos2D. So, if you want to follow along, make sure your Bitizen is 60×100 before exporting the various parts.

One thing to note is we are going to bring these into Cocos2D as 5 different sprites. There are some optimizations that you could do using sprite sheets, however I want to make things as clear as possible. So, we are going the long way.

You can download my completed white bitizen here.

Rebuilding The Bitizen In Cocos2D

Once you have imported the 5 Bitizen image files into Cocos2D, you need to reconstruct them in code. This involves adding each sprite to the layer.

Here is the code to display the skin/head+hands in our layer. As a note, I simply created a new Cocos2D project and am using the retina only mode for my display using [director enableRetinaDisplay:YES]. The offsets will change quite a bit if you are choosing to support non-retina.

<code class=’objc’>int spriteX = 240;
int spriteY = 160;

CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
[self addChild:skin];</code>

This will draw our white(shaded) head on the screen. That’s pretty boring so let’s draw the rest of the body. Update your code to look like the following:

<code class=’objc’>int spriteX = 240;
int spriteY = 160;

CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
[self addChild:skin];

int hairOffset = 11;

CCSprite *hair = [CCSprite spriteWithFile:@"hair.png"];
[hair setPosition:ccp(spriteX, spriteY+hairOffset)];
[self addChild:hair];

int shirtYOffset = -9;
int shirtXOffset = 1;

CCSprite *shirt = [CCSprite spriteWithFile:@"shirt.png"];
[shirt setPosition:ccp(spriteX + shirtXOffset, spriteY+shirtYOffset)];
[self addChild:shirt];

int pantsYOffset = -15;
int pantsXOffset = 1;

CCSprite *pants = [CCSprite spriteWithFile:@"pants.png"];
[pants setPosition:ccp(spriteX + pantsXOffset, spriteY+pantsYOffset)];
[self addChild:pants];

int shoesYOffset = -17;
int shoesXOffset = 1;

CCSprite *shoes = [CCSprite spriteWithFile:@"shoes.png"];
[shoes setPosition:ccp(spriteX + shoesXOffset, spriteY+shoesYOffset)];
[self addChild:shoes];</code>

Now, you should see the lonely ghost of a Bitizen standing in the center of your screen.

Ghost Bitizen

Still boring… Time to spice him up with some color.

Tinting Cocos2D Sprites

As I mentioned before, tinting Cocos2D sprites is very simple. I would recommend keeping all sprites that you wish to tint a shade of white/gray otherwise some crazy things will happen.

The setColor method takes an array of integers from 0-255. This array contains 3 numbers (1st for red, 2nd for green, 3rd for blue). For example, we can pass all Red to the setColor method by sending it {255,0,0}.

Let’s start by tinting our Bitizen’s shirt a random color. Change the code that displays the shirt to look like this:

<code class=’objc’>CCSprite *shirt = [CCSprite spriteWithFile:@"shirt.png"];
[shirt setPosition:ccp(spriteX + shirtXOffset, spriteY+shirtYOffset)];
ccColor3B shirtColor = {arc4random() % 255,arc4random() % 255,arc4random() % 255};
[shirt setColor:shirtColor];
[self addChild:shirt];</code>

Now, every time you run the application, the Bitizen should have a different shirt color. You can apply this principle to each of your sprites to completely customize your Bitizen.

What if you only want to limit certain colors? (you ask). Well, that’s a great question. I solved this by creating an array of ccColor3Bs. Basically an array of arrays. And then I index into this array and set the color accordingly. Here is an example of setting a random skin color to avoid having blue people (unless maybe you are making Smurfs).

<code class=’objc’>ccColor3B skinColors[] = { 
    {247,224,194},
    {255,232,214},
    {136,119,82},
    {245,232,205},
    {144,110,38}
};
CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
ccColor3B skinColor = skinColors[arc4random() % 5];
[skin setColor:skinColor];
[self addChild:skin];</code>

I have an array of 5 different arrays and randomly index into it using skinColors[arc4random() % 5]. This will give me a random color within my skin color group.

After running this through a loop and adding random colors to some of the other sprites, I ended up creating the image you see at the top of this post.

Conclusion

I hope that this tutorial has found you well and I have demystified the magic that is dynamic sprites. You may download the source code for this tutorial (include the code to generate the screenshot above) here.

If you have any questions or comments, please feel free to leave them in the comments section of this post. Also, make sure you subscribe to my RSS feed for more great tutorials!

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Pixel Art Character Tutorial – Creating And Customizing A Bitizen

This will be a continuation of my last pixel art tutorial about configuring Photoshop for Pixel Art. For the past month or so, both my wife an I have been pretty addicted to this amazing game called Tiny Tower created by Nimble Bits. The biggest draw for me to this game isn’t the fact that it has great simulation style game mechanics, it’s the fact that it was created using Pixel Art.

As I mentioned in my other post, I have a serious passion for pixel art and have been doing everything I can to learn about it and improve my skills. One great thing about it is, anyone can do it. You don’t have to be this amazing artist to be able to create interesting pixel art.

Getting Started

They say that imitation is the best form of flattery, so we are going to flatter the heck out of the Nimble Bits guys are learn how to make our own Bitizen characters from Tiny Tower. I have found that a good starting place for learning pixel art (or anything really), is to start with something that already exists, copy it, then modify it. Once you do that a few times and get comfortable, then you should have the confidence to branch out into creating your own artwork.

When creating a game (or complex piece of pixel artwork) that involves a ton of different characters, it will save a ton of time and energy if you create a “base character”. What I mean by “base character” is one that is very bland and plain. Something that is easily customizable. So, that’s what this tutorial is about, we are going to create a bland white guy for Tiny Tower.

One thing I want to point out before we start is, I have lowered the resolution of the character a bit and am not putting in as much detail as the Nimble Bits team. This is just for simplicity’s sake in order to get my point across and make things easier on you.

New Document

Start out by creating a 15x25px document. I know, it’s very small, but we don’t need much. Make sure you have Photoshop configured for pixel art. At this point, I’d suggest creating all of the layers for your bitizen. Why use layers? you might ask. Great question. Well, in order to quickly modify our base character, we want to have a separate layer for each of his features/body parts. So, create the following layers.

  • Head
  • Mouth
  • Hair
  • Eyes
  • Shirt
  • Pants
  • Feet
  • Arms

Now, you can confidently modify any part of your Bitizen without the risk of destroying the rest. As I reference each part below, make sure you switch to the correct layer when drawing.

Creating The Head

The head is perhaps the most complicated part of the Bitizen due to its odd shape and shading. The shape is due to the fact that the Bitizen is always looking in the forward direction.

Start with a skin tone color (I have used #f7e0c2) and create a 10 x 6 rectangle in the center of your view like this:

Bitizen head

Now, that the base head is in place, it’s time to draw the chin and neck. With the same color, indent one pixel in on the bottom and draw straight across. Finally, indent 3 more pixels in, and draw 4 pixels across. This is what your head should look like at this point.

Head and Chin

Shading

Shading with pixel art is simply a matter of drawing with a darker shade of your main color. With the color chooser in PS and the skin tone still selected, drag the color down to a slightly darker shade and lowlight a 1 pixel line on the right side of the face. In our example the Bitizen is looking to his right, so his left will be shaded.

Then, add some more shading as you see necessary. If you look at mine, I have used a bit of shading to extend the head a little bit.

Head Shading

Hair, Mouth And Eyes

The mouth and eyes are very simple with our Bitizens. The eyes are just single black pixels and the mouth is just a 4 pixel line using a darker shade of the skin tone.

Hair can be whatever you like. I have chosen a very simple hairstyle that you see quite often in the game with a simple shade of brown. I have also applied the same shading technique to the hair that I did to the face and neck. When you are finished, it should really start looking like a person.

Hair and eyes

Creating The Body, Legs and Feet

For the body, start with 6 x 5 rectangle set to the color that you want to make the shirt. I chose #63cfea. For the pants, simply draw a solid line. Finally, the feet are just two 2px lines spread apart by two more pixels. If you notice in the game, to animate the movement of these guys, they simply alternate between this position and a centered 4px line. It just goes to show you how much things can be simplified when you use pixel art.

Body and legs

To finish up our Bitizen, we add single pixel dots for hands and a couple pixels for arms. After that, we add a collar and some simple shading.

Here is what the completed Bitizen looks like:

Completed Bitizen

Conclusion

The one thing to remember when creating pixel art for game is to keep it simple. Simplify everything. Take for example the Toy Story characters I made at the top of this post. They are very simplistic yet you recognize who they are right away. My 2.5 year old son was yelling “Woody! Buzz!” the entire time I was creating them. I think this is one of the largest challenges; sticking to “less is more”.

There are some other fun things we can do to customize these guys. We can even do it in code! Next time, I will show you how to take a “base character” and customize its colors using Cocos 2D. This can save you even more time and energy when trying to make dynamic characters for your game.

If you are feeling lazy and want to simply download my bitizen base, click the following link:

Download my bitizen.psd template

On a final note, don’t just copy these guys for YOUR game! I know it might seem tempting to give em a different shirt and plop them in your super rad fart machine RPG, but these guys are the product of the hard work of the guys at Nimble Bits.

If you have any questions or tips, please feel free to leave them in the comments.

I would also LOVE to see some of the custom bitizens you guys come up with. Please link to them in the comments if you end up creating some.

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Configuring Photoshop For Pixel Art

First things first. My wife and I had welcomed a new baby boy into the world on Monday so you guys are going to have to see the obligatory “dad” pics.

Here they are

Jack

Jack

Ok, now that’s past us, let’s chat about pixel art. I have always been a HUGE fan of pixel art both in games and as a form of art. As an aspiring game developer (games coming soon 😉 ), I found pixel art a great fit for me. Not only is is aesthetically pleasing, it also allows developers to create “better” art than developer art. All it takes is a little patience.

Today, I’m going to share with you how I have configured Photoshop to create some pixel art and eventually show you how to make your own Bitizens from Tiny Tower in a follow up post.

Some of you might argue that Photoshop is not the way to go and that there are better tools for Pixel art. I have tried quite a few and keep coming back to PS because of some of it’s great features (shapes, layering, masks, gradients, noise filters, etc…). We can use a lot of these tools to our advantage when creating pixel art, PS just needs to be set up correctly.

Just a heads up before I start, I’m using Adobe Photoshop CS3 for Mac.

Change The Way Photoshop Scales Images

First, we need to change the way PS scales images. This is useful for when you are ready to export your sprites for production. By default, PS uses a Bicubic algorithm when you want to enlarge an image. This generally produces a very blurry effect. It’s quite useful in many cases, but terrible for pixel art. Here, we need to tell PS to use a “Nearest Neighbor” scaling algorithm. This will preserver all of our edges without PS mucking with the blending.

To change this setting, navigate to Photoshop->Preferences->General

Nearest Neighbor

The only setting you need to modify is “Image Interpolation”. Make sure to change it to “Nearest Neighbor”.

Enabling A Grid

When creating pixel art, it is very useful to have a grid in place in order to determine where to place your next pixel. Without it, you are just blindly placing them. To turn on and configure a grid in PS, navigate to Photoshop->Preferences->Guides, Grid, Slices & Count…

1px gridlines

Make sure to set Gridline every to 1 and Subdivisions to 1. This will create a 1px grid on for you to use as a guide.

Once you have configured the grid, click on View->Show->Grid to display it. You might have to do this for every document.

Configuring the Pencil Tool

When creating pixel art in PS, the pencil tool is your best friend. You will use it ~95% of the time when drawing. We need to make sure that the pencil draws single pixel dots without any interpolation. With the pencil tool selected, click the dropdown next to brush, tap the arrow and then select basic brushes. When prompted to replace current brushes, click OK.

Basic Brushes

Next, select the 1 px brush (it should be in the top left). Most of the time, you will want to draw with single pixels.

1 px brush

Creating A New Document

Deciding on a document size can be tricky. You generally want to create your document as small as possible to avoid having to do more work than you need. The size depends on how “pixellated” you want your art to look after scaling. Basically, using the scaling we chose above (nearest neighbor), the “pixels” will just increase in size.

Here is a blown up view of our 15×25 image that we will use in the next tutorial to create a Bitizen from Tiny Tower.

New Document

Since the zoom level isn’t too high, we are seeing grid slices every 2 pixels rather than 1. As you zoom, you will see the grid size increasing.

Multiple Zoom Levels In View

One cool trick with PS is, it allows you to have multiple windows of the same document open. The reason this is handy is you can see various zoom levels for your artwork all at once. While drawing each pixel zoomed in, you can see the result in the desired resolution. This helps out dramatically when you are trying to fine tune your work.

To do this, go to Window->Arrange->New Window for [projectname.psd] Now you can control the zoom level of each window individually.

In the next post, I will go over how to make these Bitizens as well as some tips for customization as an example for creating dynamic characters. We will also go over some of the basic techniques that were used.

If you have any comments, questions, or Photoshop Pixel Art Tips, please feel free to post them in the comments.

Happy coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Announcing iOS 4 In Action + Free Chapter!

Wow, I can’t believe it has been over a year since the release of my book iPhone And iPad In Action. Since then, we have sold over 6,000 copies and have just have released in numerous languages!

As with all iOS (tech books really), my book was almost outdated the moment it hit the shelves due to Apple’s constant SDK release cycle. My book ended with “here is what’s coming in iOS 4…”, and didn’t hit the shelves until after iOS 4 was released.

I was asked last year by Manning Publishing to write the 3rd version of the book to include all of the 4.0 SDK changes. Due to some huge changes in my life, I was unable to accept and they had to find the 4th author to work on the book.

Earlier this month, Jocelyn Harrington released the 3rd version of the book titled “iOS 4 In Action”. Here is a bit about this version from their site.

Written for Xcode 4, iOS 4 in Action guides you from setting up your development environment,
through coding your first app, all the way to selling in the App Store. Work through sample
applications including a chat client, a video game, an interactive map, background audio,
and more as you explore the iOS 4 SDK.

Here are some highlights about what’s inside.

  • Full coverage of iOS SDK 4.3
  • Mastering Xcode 4
  • Multitasking for iPhone and iPad
  • Game Center, iAd, and AirPrint
  • Local and push notification
  • Implementing in-app purchasing

This is a significant update and I’m really excited to get my copies in the mail. As soon as I do so, I’ll do a couple giveaways on my blog. Make sure you stick around or subscribe to the RSS feed so you don’t miss it!

Freebie

Manning is allowing anyone to download the full Chapter 21 on multitasking now for free! Go grab your copy!

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Autonomous Steering Behaviors In Corona SDK Games

Wow, it’s already been 5 months since I was last blogging for #iDevBlogADay. The time has flown by!

Recently, I have been dabbling with [Corona SDK][1] and have been getting really excited about the possibilities. For those of you who don’t know, Corona SDK is a multi platform game engine that allows you to write your code in Lua and deploy on iOS and Android devices.

Today I want to chat with you about Autonomous Steering Behaviors and show you how I have implemented a few of them in a small game that I’m working on.

Here is a short demo video of what we will be creating


Boids Demo from Brandon Trebitowski on Vimeo.

</center>

What Are Autonomous Steering Behaviors

The name does sound pretty fancy. At the core they are just behaviors that define how a character interacts with the world around them in a life-like manner. Some of the main behaviors include wandering, path following, flocking, pursing and evading. The theory and algorithms for all of these behaviors and more can be found in a paper published by Craig Reynolds in the 80’s called Steering Behaviors For Autonomous Characters.

While I admit I didn’t quite read all of it, the paper contains some incredible gems in terms of making your character AI seem much more life like.

There are plenty of examples (especially in games) where these behaviors come in handy. Perhaps the easiest behavior to implement is wander. Say for example you have an NPC (non player character) that walks around a village. The wander algorithm is a perfect fit to make it seem like that NPC is actually “thinking” about where he’s going and keeps your animations looking smooth.

The seek and evade is another interesting algorithm. Often times in our games, we want enemies to chase after us without it seeming like they have the exact shortest path to use. It adds a bit of randomness and makes your enemies seem much more realistic.

How Can I Use Them In My Corona SDK Game?

After doing a bit of research, I found this incredible site by daniel shiffman that detailed some of the algorithms using processing. This at least took the words from the paper and made them in to some code. I really suggest that you read up on that page to get a solid understanding of what we are doing here. Rather than simply regurgitating what Daniel wrote, I’m going to focus on showing you how his code can be ported for use in your Corona SDK games.

The first challenge was, the code relies heavily on using 2D vectors. Now, I didn’t see a nice built-in way to do this in Corona or Lua for that matter. So I decided to roll my own Vector2D class. For those Corona SDK veterans reading this, feel free to blast me in the comments if I’m reinventing the wheel with this and just failed to fully read the documentation. Otherwise, enjoy this Vector2D class!

Here is the link to the gist containing that file.

Here is a short snippet of that class just to add to the aesthetics of this post:

<code class=’lua’>function Vector2D:new(x, y)  – The constructor
  local object = { x = x, y = y }
  setmetatable(object, { __index = Vector2D })  – Inheritance
  return object
end

function Vector2D:normalize()
    local temp
    temp = self:magnitude()
    if temp > 0 then
        self.x = self.x / temp
        self.y = self.y / temp
    end
end

function Vector2D:dot(vec)
    return self.x * vec.x + self.y * vec.y
end</code>

Basically it’s a lua “object” that has an x and y with some helper methods for doing vector math. The lower case methods act on the current self object and the upper case methods act as static class level methods meant to return a new vector. The file is a little sloppy but it gets the job done.

Creating A Boid

In the paper, an autonomous character is called a Boid. There are basically 2 actions that we need to implement that are needed in most of the behaviors. They are steer and seek. Steer is the basis for all of the autonomous behaviors. Given a Vector2D as the target, it will return a new Vector2D for the boid’s acceleration in the direction of the target. We simply wrap this call in the seek method. Now, any behavior can call seek in order to direct the boid towards a target.

Here is a link to our Boid on github

A snippet of the wander function

<code class=’lua’>function Boid:wander()
    local wanderR = 16.0
    local wanderD = 60.0
    local change  = 0.5

    local negChange = math.random(2)
    local randomNum = math.random() * change
    if negChange == 2 then
        self.wanderTheta = self.wanderTheta - randomNum
    else 
        self.wanderTheta = self.wanderTheta + randomNum
    end 

    local circleLoc = self.vel:copy()

    circleLoc:normalize() 
    circleLoc:mult(wanderD)
    circleLoc:add(self.loc)

    local circleOffset = Vector2D:new(wanderR*math.cos(self.wanderTheta), 
        wanderR*math.sin(self.wanderTheta))
    local target = circleLoc:copy()
    target:add(circleOffset)

    self.acc:add(self:steer(target))
end</code>

What I have done is taken the code from Daniel Shiffman’s processing project and ported it directly to lua. As of right now, I have only implemented wander, however you can see how easy it is to implement other behaviors using the same techniques. Since Daniel has processing code for each of them, it’s a simple matter of making them work in your lua class.

The way wander works is, it picks random points on a circle to steer towards. These random points only vary by a fraction of a radian (defined by the change variable above) from the current steer point. The larger the change value is, the more your boid will appear jittery. This value must be tweaked to fit the wander style for your game. Based on my testing, .5 seems to generate a pretty smooth wander path.

Putting It All Together

In your own code you might want to build directly on top of my boid class or subclass it for each boid type. In the following example, I’m going to show you how to simply run our boid class and watch some dots wander around (hang on to your hats).

Here is a link to main.lua on github, but I have also pasted it here so we can talk about it.

<code class=’lua’>local Boid = require(‘Boid’)

– Define some limiting constants
MAX_FORCE = 1.75
MAX_SPEED = 2.0

local wanderers = {}

function animate(event) 
    for i=1,#wanderers do
        local wanderer = wanderers[i]
        wanderer:wander()
        wanderer:run()
    end
end

function Main()
    math.randomseed( os.time() )
    
    for i=1,10 do
        local loc = Vector2D:new(display.contentWidth / 2,display.contentWidth / 2)
        local wanderer = Boid:new(loc,MAX_FORCE,MAX_SPEED)
        table.insert(wanderers,wanderer)
    end
    
    Runtime:addEventListener( "enterFrame", animate );
end

Main()</code>

Here we declare an array of wanderers. In the Main() method we initialize each one, insert them into the array, and add a hook to call our animate method for each frame. Inside of the animate method, we simply tell each wanderer to wander and then run itself. The boid class will take care of the rest.

One thing to note is, the boids are unaware of each other at this time. That requires a cohesion method. I have it written and might post it up at a later time; I just want to keep things simple for now. Please feel free to ask me questions in the comments or write me on Twitter.

You can download or fork the full source for this project here.

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

[1]: http://www.anscamobile.com/corona/