Iphone SDK:移动并旋转触摸 [英] Iphone SDK: move and rotate to touch

查看:141
本文介绍了Iphone SDK:移动并旋转触摸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条鱼的图像 - 如果用户触摸屏幕,我希望鱼看到触摸点并移动到那里。如果触摸已被移动,我希望鱼不断触摸。

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.

我该怎么做?

推荐答案

将是这样的:

- (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

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

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

这篇关于Iphone SDK:移动并旋转触摸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆