I am trying to let the finger drag CCSprite with the following code:
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedCoordinate = [[CCDirector sharedDirector] convertToGL:location];
CGRect redCircleRect = CGRectMake(redCircle.position.x, redCircle.position.y, redCircle.contentSize.width, redCircle.contentSize.height);
CGRect redCircle2Rect = CGRectMake(redCircle2.position.x, redCircle2.position.y, redCircle2.contentSize.width, redCircle2.contentSize.height);
if(CGRectContainsPoint(redCircleRect, convertedCoordinate)) {
//redCircle.position = ccp(convertedCoordinate.x, convertedCoordinate.y);
NSLog(@"Touched");
spriteIndex = 1;
}
else if(CGRectContainsPoint(redCircle2Rect, convertedCoordinate)) {
//redCircle2.position = ccp(convertedCoordinate.x, convertedCoordinate.y);
NSLog(@"Touched2");
spriteIndex = 2;
}
else {
spriteIndex = 0;
}
return YES;
}
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedCoordinate = [[CCDirector sharedDirector] convertToGL:location];
if (spriteIndex == 1) {
redCircle.position = ccp(convertedCoordinate.x, convertedCoordinate.y);
}
else if (spriteIndex == 2) {
redCircle2.position = ccp(convertedCoordinate.x, convertedCoordinate.y);
}
//CGRect RedCircleRect = CGRectMake(redCircle.position.x, redCircle.position.y, redCircle.contentSize.width, redCircle.contentSize.height);
//CGRect RedCircle2Rect = CGRectMake(redCircle.position.x, redCircle.position.y, redCircle.contentSize.width, redCircle.contentSize.height);
}
My logic is as follows:
In ccTouchesBegan
I get the location of the touch, convert it to the right coordinates, then make two CGRect's that are, supposedly, the same dimensions and location of the two sprites I have declared. Then, I check if the finger is touching one of those two rectangles using CGRectContainsPoint
. In there, I have a global int called spriteIndex
that I assign a value according to what circle was touched.
Next, in ccTouchesMoved
I check if spriteIndex
has been given the "index" of one of the two sprites I am trying to move, and if so, set the location of the sprite that is selected to the touch location.
The Problem:
This code only sort of works. It lets me drag the CCSprites, but only if I click the center. And the sprite is 40 by 40 pixels, so it is by no means small.