# Falling images that can be pressed

In my cocos2d app I am trying to make images fall from the top of the screen and detect when they are pressed. I am having a hard time. Can anyone help me achieve this? Thanks.

Once you have implemented some touch delegate you can easely tell if you touched your sprite or not using bounding boxes, doing something like:

    if (CGRectContainsPoint(touchPoint, [sprite boundingBox])){

}


I am going to do a language and platform independent approach here.

All images should be represented as rectangles. Rectangles are usually just 4 elements long arrays that look like this: [x, y, width, height].

x and y represent the position of the image. If you want the image to have a falling effect, ie to move downwards, they you will want to increase the y coordinate gradually (the y axis increases "downwards" in computer graphics, remember that).

The width and height, obviously, represent the dimensions of the image.

A click can be represented by two numbers, just the x and y, as it is actually just a point in space, it doesn't have any dimensions.

Now, your problem is essentially checking whether the click happened inside the image. How do you do that?

Well, like this:

//xc = click x
//yc = click y
//rect = [x, y, width, height]

if (xc >= rect[0] && xc <= rect[0] + rect[2] && yc >= rect[1] && yc <= rect[1] + rect[3])
{
//Click happened.
}
else
{
//The click was outside of this particular image.
}


If you don't understand the code, tell me what is bothering you in a comment and I will explain further.

• This is cocos2d for iOS. I am trying to have images fall from the top of the screen and the user of the application is trying to press them. – Coder404 Jul 6 '12 at 20:54