Question

I want to detect, what part of screen is touched, when user shakes iPhone.

I do it in the following way:

-(void) accelerometer: (UIAccelerometer*)accelerometer didAccelerate: (UIAcceleration*)acceleration
{
    float shakeStrength = sqrt( acceleration.x * acceleration.x + acceleration.y * acceleration.y + acceleration.z * acceleration.z );

    if (shakeStrength >= 1.5f)
    {
        if (isLeftHandTouches && isRightHandTouches)
        {
            DebugLog(@"both hands shake");
        } else if (isLeftHandTouches)
        {
            DebugLog(@"left hand shake");
        } else if (isRightHandTouches)
        {
            DebugLog(@"right hand shake");
        }
    }
}

-(void) touchesBegan: (NSSet *)touches withEvent: (UIEvent *)event
{
    NSSet *allTouches = [event allTouches];

    for (int i = 0; i < [allTouches count]; i++)
    {
        if ([ [ [allTouches allObjects] objectAtIndex: i] locationInView: [self view] ].x <= 240.0f)
        {
            isLeftHandTouches = YES;
        } else
        {
            isRightHandTouches = YES;
        }
    }
}

-(void) touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event
{
    NSSet *allTouches = [event allTouches];

    for (int i = 0; i < [allTouches count]; i++)
    {
        if ([ [ [allTouches allObjects] objectAtIndex: i] locationInView: [self view] ].x <= 240.0f)
        {
            isLeftHandTouches = NO;
        } else
        {
            isRightHandTouches = NO;
        }
    }
}

Everything works fine if user removes both hands before making another shake, but everything gets messed up if I have both hands on the screen and remove one of them.

i.e. I shake with both hands on the screen and afterwards I want to shake the iPhone with only one hand. In this case the shake won't count - as if there no touches on the screen. I assume that when I remove one hand from the screen, both "touches" are being removed.

What is the problem and how can I fix it?

Thanks.

Was it helpful?

Solution

Why are you enumerating over -allTouches? Just enumerate over the touches set that is passed in. The same goes for both methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top