我正在开发一个简单的游戏,其中“粒子”吸引了用户的触摸。

- (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;
    }
}
lastTouchesCGPoint的数组,程序的另一部分用来移动粒子。

我遇到的问题是,现在设置的方式是,无论何时调用这三个函数中的任何一个,它们都会覆盖CGPoints数组和numberOfTouches。我不认为这会是一个问题,但事实证明TouchesMoved仅会获得已更改的触摸,而不会获得保持不变的触摸。结果,如果您移动一根手指而不是另一根手指,则该程序会忘记没有移动的手指,并且所有粒子都移向移动的手指。如果移动两个手指,粒子将在两个手指之间移动。

我需要以某种方式在更新有触感的同时保持触感。

有什么建议?

最佳答案

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将保存自开始以来从未移动过的触摸。您可以忽略其中一个或两个变量,也可以忽略所有您不关心的语句。

10-08 07:46