我试图让手指用以下代码拖动CCSprite:
-(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);
}
我的逻辑如下:
在ccTouchesBegan
中,我得到触摸的位置,将其转换为正确的坐标,然后制作两个CGRect,它们应该与我声明的两个精灵的尺寸和位置相同。然后,我使用CGRectContainsPoint
检查手指是否正在接触这两个矩形中的一个。在那里,我有一个名为spriteIndex
的全局int,我根据触摸的圆圈分配一个值。
接下来,在ccTouchesMoved
中,我检查spriteIndex
是否已经给出了我想要移动的两个精灵之一的“索引”,如果是,请设置精灵的位置,即选择到触摸位置。
问题:
这段代码只是有点工作。它允许我拖动CCSprites,但仅当我单击中心时。精灵是40 x 40像素,所以它绝不是小的。
答案 0 :(得分:0)
在another forum找到答案:
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);
应该是:
CGRect redCircleRect = CGRectMake(redCircle.position.x-20.0, redCircle.position.y-20.0, 40.0, 40.0);
CGRect redCircle2Rect = CGRectMake(redCircle2.position.x-20.0, redCircle2.position.y-20.0, 40.0, 40.0);
这是因为,CGRect副本是从中心指针创建的,它应该从左下角开始。