我正在开发一款简单的游戏,其中“粒子”被用户触摸所吸引。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *touch = [touches allObjects];
for (numberOfTouches = 0; numberOfTouches < [touch count]; numberOfTouches++) {
lastTouches[numberOfTouches] = [((UITouch *)[touch objectAtIndex:numberOfTouches]) locationInView:self];
}
isTouching = YES;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *touch = [touches allObjects];
for (numberOfTouches = 0; numberOfTouches < [touch count]; numberOfTouches++) {
lastTouches[numberOfTouches] = [((UITouch *)[touch objectAtIndex:numberOfTouches]) locationInView:self];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *touch = [touches allObjects];
for (numberOfTouches = 0; numberOfTouches < [touch count]; numberOfTouches++) {
lastTouches[numberOfTouches] = [((UITouch *)[touch objectAtIndex:numberOfTouches]) locationInView:self];
}
if (!stickyFingers) {
isTouching = NO;
}
}
lastTouches
是CGPoint
的数组,程序的另一部分用于移动粒子。
我遇到的问题是我现在设置它的方式,无论何时调用3个函数中的任何一个,它们都会覆盖CGPoints数组和numberOfTouches。我不认为这会是一个问题,但事实证明,TouchesMoved只能获得已经改变的触摸并且没有得到保持不变的触摸。因此,如果您移动一根手指而不是另一只手指,则程序会忘记手指没有移动,所有粒子都朝向移动的手指。如果你移动两个手指,粒子就会在两个手指之间移动。
我需要在保持更新已经移动的触摸时保持尚未移动的触摸。
任何建议?
答案 0 :(得分:1)
Set theory救援!
//Instance variables
NSMutableSet *allTheTouches;
NSMutableSet *touchesThatHaveNotMoved;
NSMutableSet *touchesThatHaveNeverMoved;
//In touchesBegan:withEvent:
if (!allTheTouches) {
allTheTouches = [[NSMutableSet alloc] init];
touchesThatHaveNotMoved = [[NSMutableSet alloc] init];
touchesThatHaveNeverMoved = [[NSMutableSet alloc] init];
}
[allTheTouches unionSet:touches];
[touchesThatHaveNotMoved unionSet:touches];
[touchesThatHaveNeverMoved unionSet:touches];
//In touchesMoved:withEvent:
[touchesThatHaveNeverMoved minusSet:touches];
[touchesThatHaveNotMoved setSet:allTheTouches];
[touchesThatHaveNotMoved minusSet:touches];
//In touchesEnded:withEvent:
[allTheTouches minusSet:touches];
if ([allTheTouches count] == 0) {
[allTheTouches release]; //Omit if using ARC
allTheTouches = nil;
[touchesThatHaveNotMoved release]; //Omit if using ARC
touchesThatHaveNotMoved = nil;
}
[touchesThatHaveNotMoved minusSet:touches];
[touchesThatHaveNeverMoved minusSet:touches];
在上文中,touchesThatHaveNotMoved
将保留在最后touchesMoved:
内没有移动的触摸,而touchesThatHaveNeverMoved
将保留自开始以来一直没有移动过的触摸。您可以省略一个或两个变量,以及您不关心的所有涉及它们的语句。