问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/5653682/iphone-sdk-move-and-rotate-to-touch