iPhone:使用touchesBegan,touchesMoved和touchesEnded平移移动图像

时间:2010-10-01 18:17:49

标签: iphone input

我在视图中有一个包含9x9网格的图像。我想使用平移运动沿着网格移动对象,网格由另一个数组(9)内的列数组(9)组成。图像应在网格中从正方形移动到正方形。下面的代码是我到目前为止的代码。问题是图像一次跳跃3-4个方格。它太敏感了。任何人都可以解释为什么,并就如何解决这个敏感性问题提出一些建议吗?

有效的代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    gestureStartPoint = [touch locationInView:self.view];

    // Do not move if touch is off the grid
    if (gestureStartPoint.x < 0 || 
        gestureStartPoint.x > 450 || 
        gestureStartPoint.y < 0 || 
        gestureStartPoint.y > 450) {
        canMove = NO;
    }else {
        canMove = YES;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];   

    double thresholdX = 50;

    if (canMove) { 
        deltaX = (int)(currentPosition.x - gestureStartPoint.x); 
        if (deltaX > thresholdX) {
            deltaX = 0; 
            if([self blockCanMoveXDir:1]){
                [cBlock movX:1];
            }
            // Resets start point 
            gestureStartPoint = currentPosition; 
            NSLog(@"-------------> Block Moved"); 
        } else if(deltaX < 0 && fabs(deltaX) > thresholdX) {
            deltaX = 0; 
            if([self blockCanMoveXDir:-1]){
                [cBlock movX:-1];
            }
            gestureStartPoint = currentPosition; 
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    canMove = NO;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    canMove = NO;
}

1 个答案:

答案 0 :(得分:1)

我认为在if (canMove) {以下你应该积累动作。让我解释一下,你应该用这种方式计算运动的绝对deltaX:

deltaX = currentPosition.x - gestureStartPoint.x;

其中deltaX是一个类变量。当此值大于阈值时,您将执行单块移动。调整该阈值可以改变灵敏度。 当然,您还必须考虑Y分量。