sábado, 24 de marzo de 2012

COCOS2D - Check if your sprite is touched and then drag and drop

If you want to drag and drop your sprite only if you touch it you can use this function. My sprite dimensions are 14x14, that's why I check +- 7.


-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
   
   
    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView: touch.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
   
    if (isFirstTouch)
    {
   
        if (( (touchLocation.x >= (mySprite.position.x - 7)) &&  (touchLocation.x <= (mySprite.position.x +7) )) &&  ( (touchLocation.y >= (mySprite.position.y - 7)) &&  (touchLocation.y <= (mySprite.position.y +7) )))
        {        
            [mySprite setPosition:ccp(touchLocation.x , touchLocation.y )];
           isFirstTouch = NO;
        }
    }
    else
    {      
        [mySprite setPosition:ccp(touchLocation.x , touchLocation.y )];
}




- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    isFirstTouch = YES;
}

No hay comentarios: