One of the most basic tasks you will want to do when creating any Cocos2D game is create Sprites. All of your characters, targets and objects are made up of sprites.
In this example you'll be creating a basic sprite (in the form of a gift box or present), and adding some basic movement so that our sprite is spawned randomly and falls from the top to the bottom of the screen with a bit of a jiggling motion. This is the exact principle I used to create one of my free games on the iTunes store; The Anti-Claus.
Start off by grabbing the sprite image file for this example from here: http://boydlee.com/images/present1.png, alternatively right-click and download the image as displayed below.

1) Create a new Cocos2D project and in the 'init' method of your "HelloWorldScene.m" file, first remove all the existing sample code and then paste in the following:
What we are doing here is declaring our CCSprite object and passing in the location of our sprite image file (present1.png) along with the width and height of that image. You'll also note that we have created a winSize object that holds the dimensions of the screen in pixels - this is better than hard coding values as you'll be able to get more reuse out of your code by creating games that can run on multiple resolutions (e.g. iPhone and iPad).
2) Make sure you drop the 'present1.png' image you download into your Resources directory of the project first (opting to 'Copy Resources Into Folder' if it is not already checked) and then run your project in the simulator. You should end up with the following on your screen:
3) Now let's add action to our sprite that makes it appear to be 'wiggling', using the CCRotate method.
4) We want our present sprite to float from the top of screen to the bottom, and to do this we use the CCMove method. Here in the sample below we create our 'move' action, give it a duration of 2.0 (seconds) and tell the move action to move our present sprite from its current 'y' position to y-position of -50px, which will put it off screen. You'll also notice that we are creating an 'action move completed' method which will remove the sprite from memory and perform cleanup once the action has completed and the sprite has reached -50px on the y-axis.
That's it - you should now be able to run your project and see a sprite being created, and then moving from the middle of the screen to off the bottom.
In the next article I'll show you how we create a game loop using a timer and use that to spawn multiple present sprites that appear on the screen at random positions, as well as introducing touch events!
Posts: 1
Reply #1 on : Thu January 12, 2012, 05:22:43