简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM