2

I am using Cocos2D to develop a mini iPhone game.. I wanted to detect the touch of a sprite. To do so I decided not to subclass the CCSprite class but instead using the touch events in the layer class:

-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CCLOG(@"touch began...");
    CCSprite *particularSprite = [self getChildByTag:artSprite];
    CCNode *nodeClass = (CCNode*) particularSprite;
    CGRect DesiredSprite = CGRectMake(nodeClass.positionInPixels.x,  nodeClass.positionInPixels.y,particularSprite.contentSize.width  , particularSprite.contentSize.height);

    for (UITouch *myTouch in touches) {
        CGPoint touchPosition = [myTouch locationInView: [myTouch view]];
        if(CGRectContainsPoint(DesiredSprite ,touchPosition ))
        {
            CCLOG(@"Sprite touched");
        }
    }
}

Unfortunately the coordinates are wrong. The locationInView translates it differently. I am using the landscapeleft view (kCCDeviceOrientationLandscapeLeft).

Adding a breakpoint on the function and looking at the myTouch variable, then I see that it has a member variable called locationInWindow which reflects the actual touch position (which is what I want).

I tried to access to the locationInWindow but there is no getter method for it. How can I do so?

Many thanks and Best Regards

mm24
  • 9,280
  • 12
  • 75
  • 170

1 Answers1

5

Window is a UIWindow which is a UIView subclass. Additionally UITouch has a window property. So you could try:

CGPoint touchPosition = [myTouch locationInView:myTouch.window];

The view's transform figures into the calculation; So you might also want to try self.superview for the parameter.

NJones
  • 27,139
  • 8
  • 70
  • 88
  • Hi, thanks, It did help.. I had to translate the position swapping x to y as of the landscape view.. was wondering if there was an automated way to do so.. I did use the boundingBox rectangle to compare against as creating the rectangle as previously done was not precise (it was not created with the origin point in x and y as a sprie). Thanks :)! – mm24 Feb 11 '12 at 18:37
  • 2
    also, the documentation notes that you can pass `nil` to get the coordinates in the window. – adam.wulf Feb 12 '13 at 23:13