Search code examples
iphoneimagerotationtouchmove

Iphone SDK: move and rotate to touch


I have an image of a fish - If the user touches the screen I want the fish to "look" at the touched point and move there. If the touch has been moved i want the fish constantly following the touch.

How can I do that?


Solution

  • would be something like this:

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *tap = [touches anyObject];
        CGPoint pointToMove = [tap locationInView:self.view];
    
        CGFloat xdiff = pointToMove.x-myFish.center.x;
        CGFloat ydiff = pointToMove.y-myFish.center.y;
    
        if (!CGRectContainsPoint(myFish.frame, pointToMove)) {
            CGFloat angle = 0;
            if (xdiff) {
                if (xdiff>0) {
                    angle = atanf(ydiff/xdiff);
                } else {
                    angle = M_PI + atanf(ydiff/xdiff);
                }
            }
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.3f];
            [UIView setAnimationBeginsFromCurrentState:YES];
            [UIView setAnimationCurve:UIViewAnimationCurveLinear];        
            myFish.transform = CGAffineTransformMakeRotation(angle);
            [UIView commitAnimations];
        } 
    
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0f];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];    
        myFish.center = pointToMove;
        [UIView commitAnimations];
    }
    

    and you probably want to implement these too:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    

    EDIT: updated code, now the rotation is done in a separate animation, so that the fish rotates faster than he swims.