views:

47

answers:

3

First i have scaled the layer larger which contains the sprites. Now I need to sense touch on a sprite. I have tried as follows, but cant reach to goal-

CGRect tRect= [[aSprite displayedFrame] rect];
    if(CGRectContainsPoint(tRect, touchedPosition))
{
    NSLog(@"touched:>> touch at (%f,%f)",touchedPosition.x,touchedPosition.y);
    // Do something, maybe return kEventHandled;
}
else{
    NSLog(@"NOT touched: touch at (%f,%f)",touchedPosition.x,touchedPosition.y);
}

FYI: I have used cocos2d framework

+1  A: 

First, you need to make sure you get the location from the UITouch correctly.

CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

Second, you need to test your touch against the sprite's bounding box.

if (CGRectContainsPoint([sprite boundingBox], location)) {
    // The sprite is being touched.
}
Frank Mitchell
@Mitchell, I have already done that.
Sadat
@Mitchell, thanks for your response
Sadat
A: 

Frank Mitchell is correct. Another approach would be to add your listening code to the sprite itself so that Cocos will do the work for you. It will only send the sprite ccTouchesBegan events if it is actually touched.

cc
thanks @cc, i will try this technique...
Sadat
A: 

At last I have found the solution :), here is the code

CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

CGPoint tapPosition = [self convertToNodeSpace:convertedLocation];

where 'self' is the sprite holder layer as I have specified before. This layer is listening the touch event.

Sadat