Home > Category > Getting touched

Getting touched

I had an opportunity last night to work on the input component of uSightRead. The main part of the game is a single scene, with layers for the individual parts. There is a main game display layer and an input layer. The input layer consists of keys from a piano that respond to touches. Initially I had thought that each sprite would be able to handle its own touches and then simply pass a message up. This is not how it works. With cocos2d-iphone only a layer can receive touches. I discovered this in a answer to this question on Stack Overflow, which the answer goes into how to do bounds checking.

If you note the highest rated answer shows how to compute where the point touched within your layer, and then determine if the touch was inside a label. This is doing a basic rectangle point intersection. The example code uses a compound if statement, but I simply built a rectangle based on my sprite, and used the CGRectContainsPoint function found. You can read about the built-in geometry functions here. Here’s what my code looks like:

CGRect spriteRect =
  CGRectMake(self.position.x - spriteWidth / 2,
                   self.position.y - spriteHeight / 2,
                   spriteWidth,
                   spriteHeight);

if(CGRectContainsPoint(spriteRect, cLoc)
{
  NSLog(@"Sprite was touched");
  return kEventHandled;
}
else
{
  return kEventIgnored;
}

The one thing to note is the subtraction of half the width and height to compute the postion. This is because the position is actually the center of the Sprite.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  1. Sean Carmody
    June 18th, 2009 at 00:20 | #1

    Thanks for posting this – it has been a point of confusion to many. Just to make completely clear, does the object to be tested fr touch need to be on a layer by itself? Or just on a layer in general, that may contain other sprites and objects?

    Thanks again.

  2. June 18th, 2009 at 08:09 | #2

    The way I have it setup, there is only one sprite in the layer and that is the sprite that I’m checking to see if the touch is in. There’s no reason that you can’t have more than one sprite in the layer, or really any other CocosNode. If you want to check for touches in each of the sprites, then you’d simply loop over them and check them individually.

    One thing to note (which I discovered last week) is that if you have the layer position set to something other than the center of the screen, then you have to do a transformation to get the actual (screen relative) point that can be compared against the point you get from the touch (after converting it with the convert coordinate like in the linked example). Fortunately there’s a message for that named -(CGPoint) convertToWorldSpace:(CGPoint)nodePoint that’s part of the CocosNode base class.

  1. No trackbacks yet.