2011-04-13 97 views
0

我有一条鱼的图像 - 如果用户触摸屏幕,我希望鱼“看”在触摸点,并在那里移动。如果触摸已经移动,我希望鱼不断跟随触摸。Iphone SDK:移动并旋转触摸

我该怎么做?

回答

4

会是这样的:

- (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]; 
} 

,你也只需要实施这些:

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

编辑:更新的代码,现在旋转在一个单独的动画完成,这样鱼的转动速度比他游泳的速度快。

+1

让鱼“看”你的手指,你会检查是否触摸是从目前的鱼的位置是正确的还是左侧,然后用另一个替换图像 – 2011-04-13 18:35:35

+0

我以前做过,但我不想取代图像 - 我想能够旋转图像360度。 – DailyDoggy 2011-04-13 18:52:34

+1

这是目前不完全正确的,但您会了解如何做到这一点。我的学位计算有些不对,但我无法弄清楚。 – 2011-04-13 19:54:13