<div class="posterous_bookmarklet_entry"> > <div>
In the previous tutorial I wrote about scenes and layers, the basic structural classes of a cocos2d app. In this next installment, I’m going to talk about putting some actual content into your scenes and responding to user input.
If we’re interested in getting user input, first we should create something that responds to that input. In most cases, this will be a sprite object. A sprite is usually a representation of an entity in your game system, such as the player, an enemy, or a power-up. When you create a new sprite, you give the sprite an image as a parameter. After you add the sprite to a containing layer, that image then appears on the screen, and you can move it around by manipulating properties of the sprite object. A simple example:
CCSprite *mySprite = [CCSprite spriteWithFile:@``"Icon.png"``];
[mySprite setPosition:ccp(160, 240)];
[self addChild:mySprite z:1];
This is the easiest way to get an image onto the screen. Once you’ve created a sprite, you can transform it in various ways.
[mySprite setPosition:ccp(30, 30)]; ``// Change position
[mySprite setScale:2.0]; ``// Make 2x bigger
[mySprite setRotation:180.0]; ``// Rotate
Wait, this post was supposed to be about detecting user touches, right? OK, let’s create an example app that will use the ubiquitous “pinch” gesture to scale a sprite that’s displayed in the center of the screen.
Create a new project using the regular cocos2d template. I named mine “TouchExample.” Open up the Classes group in the Groups & Files sidebar, click on the HelloWorldScene.h file, then modify the class declaration as follows:
@interface HelloWorld : CCLayer
@property (nonatomic, retain) CCSprite *mySprite;
// returns a Scene that contains the HelloWorld as the only child
Basically what you’re doing here is creating a reference to a sprite object that can be accessed from any method in the HelloWorld layer. That means you can create the sprite in your “init” method, then reference it and move it around in a different method later. Next, open the HelloWorldScene.m file. Navigate to the “init” method, and replace the code there:
// Creates "setters" and "getters" for this sprite
((self = [super init]))
// ask director the the window size
CGSize size = [[CCDirector sharedDirector] winSize];
// Set layer to respond to touch events
// Create sprite and add to layer
mySprite = [CCSprite spriteWithFile:@``"Icon.png"``];
[mySprite setPosition:ccp(size.width / 2, size.height / 2)];
What we’re doing here is telling the layer that we want it to respond to touches. Then we create a sprite using the app icon and slap it in the center of the screen. Next, add the following methods after “init.” When you called the “setIsTouchEnabled” method of the layer in the init method, the following three methods are available to be overridden with your own logic.
- (``void``)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
// Override the "ccTouchesMoved:withEvent:" method to add your own logic
- (``void``)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
// This method is passed an NSSet of touches called (of course) "touches"
// "allObjects" returns an NSArray of all the objects in the set
NSArray *touchArray = [touches allObjects];
// Only run the following code if there is more than one touch
([touchArray count] > 1)
// We're going to track the first two touches (i.e. first two fingers)
// Create "UITouch" objects representing each touch
UITouch *fingerOne = [touchArray objectAtIndex:0];
UITouch *fingerTwo = [touchArray objectAtIndex:1];
// Convert each UITouch object to a CGPoint, which has x/y coordinates we can actually use
CGPoint pointOne = [fingerOne locationInView:[fingerOne view]];
CGPoint pointTwo = [fingerTwo locationInView:[fingerTwo view]];
// The touch points are always in "portrait" coordinates
// You will need to convert them if in landscape (which we are)
pointOne = [[CCDirector sharedDirector] convertToGL:pointOne];
pointTwo = [[CCDirector sharedDirector] convertToGL:pointTwo];
// Get the distance between the touch points
distance = ``sqrt``(``pow``(pointOne.x - pointTwo.x, 2.0) + ``pow``(pointOne.y - pointTwo.y, 2.0));
// Scale the distance based on the overall width of the screen (multiplied by a constant, just for effect)
scale = distance / [CCDirector sharedDirector].winSize.width * 5;
// Set the scale factor of the sprite
- (``void``)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
You can see that there are three phases we can use to get info about user touches: touchesBegan, touchesMoved, and touchesEnded. Right now we’re only concerned about what happens when touches move around the screen, so the other two methods just have logging statements in them to prove that they’re firing.
The ccTouchesMoved: method is automatically given an NSSet of UITouch objects when it is called. You can see in the commented code how those objects are converted down into CGPoint structs that contain regular Cartesian coordinates, which can then be used in a meaningful way. If your game is set up to run in landscape mode (or can toggle between portrait and landscape), you’ll need to send the CGPoint coordinates to the CCDirector to be converted to the current orientation. However, if your game is portrait-only (like, ahem, Nonogram Madness), you can omit that step.
Once the x/y values of the two touch points are obtained, they get plugged into the Pythagorean theorem to find the distance between them. That distance is scaled by the total screen width, then applied to the sprite as a scaling factor.
The last step that needs to be taken is that we need to tell the app that it should recognize multiple touches. To do that, open up TouchExampleAppDelegate.m and find where the OpenGL view is created (do a search for “EAGLView *glView”). After the long initialization, type:
Build & run the project in the iOS simulator, and hold down the Option key to make two touch points with your mouse. You can see that the sprite scales up and down based on the distance between the touches.
Congrats! You have the basics of getting user input in your cocos2d app. Play around with the project and see what other sorts of ways you can manipulate the sprite. One problem with this example is that the sprites’ scale factor is reset each time you touch the screen again. An interesting reader exercise might be to retain the scale factor, so that the interaction feels more “natural.” I’ve attached my solution (which is probably needlessly complex) in an Xcode project file.
<div> <div>[<span>←</span> Nonogram Madness 1.1](http://ganbarugames.com/2010/12/nonogram-madness-1-1/)</div> <div>[My Photoshop Replacement <span>→</span>](http://ganbarugames.com/2010/12/my-photoshop-replacement/)</div> </div>
Wow… multitouch with cocos2d-iphone