Search code examples
cocos2d-iphonetouchcgrect

cocos2d ccTouchesMoved moving sprite only to top right corner


Forgive my elementary question as I'm pretty new to cocos2d, but I'm having an issue moving a sprite around. The method seems to do what I want...as long as it's moving in a positive x and positive y direction (top right corner). If I try to move it down or left, it doesn't work.

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *myTouch = [touches anyObject];
    CGPoint point = [myTouch locationInView:[myTouch view]];
    point = [[CCDirector sharedDirector] convertToGL:point]; //create point location
    CCNode *sprite = [self getChildByTag:kTagSprite]; //set sprite
    CGRect spriteRect = CGRectMake(sprite.position.x, sprite.position.y, sprite.contentSize.width, sprite.contentSize.height); //create box around sprite and get position
    if(CGRectContainsPoint(spriteRect, point)){
        [sprite setPosition:point];  //if my pointer is inside of the sprite box, move the sprite
    }
}

Thank you.

edit: adding my init and tag reference

-(id) init{
    if((self = [super init])){
        self.isTouchEnabled = YES;
        CCSprite *mySprite = [CCSprite spriteWithFile:@"sprite.png"];
        mySprite.position = ccp(240, 40);
        [self addChild:mySprite z:0 tag:kTagSprite];
    }
    return self;
}

and i declared the kTagSprite in:

enum{
    kTagSprite
};

Solution

  • -(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *myTouch = [touches anyObject];
        CGPoint point = [myTouch locationInView:[myTouch view]];
        point = [[CCDirector sharedDirector] convertToGL:point]; //create point location
        CCSprite *sprite = [self getChildByTag:kTagSprite]; //set sprite
    
        if(CGRectContainsPoint([sprite boundingBox], point)){
            [sprite setPosition:point];  //if my pointer is inside of the sprite box, move the sprite      CCLOG(@"THIS WILL BE CALLED");
        }
    }
    

    run the code and look at the console to see if the log will be called..