Question

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

Was it helpful?

Solution 3

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.

OTHER TIPS

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 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top