Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move UIView With Deceleration

I have a need to tap and drag a UIView on the screen with deceleration. I have written the code very nicely for moving the view with touches, but need the object to keep moving with a certain degree of inertia (once a certain acceleration threshold is met), decelerating until it stops, or meets the boundary of the screen. This is not for a game, but using some standard UIView controls. The biggest part I am grappling with is the acceleration.

Any good algorithms that you have written to accomplish the same?

Edit:

I am using an animation block on the touchesEnded: method, but there is a noticeable delay between the time that a person lets go of their finger and the animation kicks in:

[UIView transitionWithView:self 
                  duration:UI_USER_INTERFACE_IDIOM() == 
                               UIUserInterfaceIdiomPhone ? 0.33f : 0.33f * 2.0f
                   options:UIViewAnimationCurveEaseOut 
                animations:^(void){
                        if (dir == 1)   //  Flicked left
                        {
                            self.center = CGPointMake(self.frame.size.width * 0.5f,
                                                      self.center.y);
                        }
                        else {  //  Flicked right
                            self.center = CGPointMake(
                                self.superview.bounds.size.width - 
                                  (self.frame.size.width * 0.5f), self.center.y);
                        }
                     } 
                completion:^(BOOL finished){
                     // Do nothing
                }];
like image 710
Wayne Hartman Avatar asked Feb 27 '11 04:02

Wayne Hartman


2 Answers

The problem is in the timing function used for the animation. The animation should be as fast as the user's dragging in the first, and quickly decelerates. The following code shows a very simple example of implementing this behavior.

First, in my touchesBegan:withEvent: method, I recorded the first touch location to my point buffer. I'm buffering two touch locations to get the movement vector of the view, and there could be different ways of getting the vector.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    ivar_lastPoint[0] = [[touches anyObject] locationInView:self];
    ivar_lastPoint[1] = ivar_lastPoint[0];
    ivar_touchOffset.x = ivar_lastPoint[0].x - self.sprite.position.x;
    ivar_touchOffset.y = ivar_lastPoint[0].y - self.sprite.position.y;
    self.lastTime = [NSDate date];
} 

Then, in touchesMoved:withEvent: method, I updated the location of the view. Actually, I used a CALayer rather than a view, as I want to use a custom timing function for its animation. So, I update the location of the layer according to the user, and for a given interval, I update the location buffers.

#define kSampleInterval 0.02f

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    /* First of all, move the object */
    CGPoint currentPoint = [[touches anyObject] locationInView:self];
    CGPoint center = self.sprite.position;
    center.x = currentPoint.x - ivar_touchOffset.x;
    center.y = currentPoint.y - ivar_touchOffset.y;
    self.sprite.position = center;

    /* Sample locations */
    NSDate *currentTime = [NSDate date];
    NSTimeInterval interval = [currentTime timeIntervalSinceDate:self.lastTime];
    if (interval > kSampleInterval) {
        ivar_lastPoint[0] = ivar_lastPoint[1];
        ivar_lastPoint[1] = currentPoint;
        self.lastTime = currentTime;
        self.lastInterval = interval;

    }
    [CATransaction commit];
}

self.sprite is a reference to the CALayer object on my view. I don't need animation for dragging so I disabled it by using CATransaction class object.

Finally, I calculate the vector and apply the animation in touchesEnded:withEvent: method. Here, I created a custom CAMediaTimingFunction, so it's really "fast-in, ease-out".

#define kDecelerationDuration 1.0f
#define kDamping 5.0f

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint targetPoint;
    NSDate *currentTime = [NSDate date];
    NSTimeInterval interval = self.lastInterval + [currentTime timeIntervalSinceDate:self.lastTime];
    targetPoint.x = self.sprite.position.x + (ivar_lastPoint[1].x - ivar_lastPoint[0].x)/interval*kDecelerationDuration/kDamping;
    targetPoint.y = self.sprite.position.y + (ivar_lastPoint[1].y - ivar_lastPoint[0].y)/interval*kDecelerationDuration/kDamping;
    if (targetPoint.x < 0) {
        targetPoint.x = 0;
    } else if (targetPoint.x > self.bounds.size.width) {
        targetPoint.x = self.bounds.size.width;
    }
    if (targetPoint.y < 0) {
        targetPoint.y = 0;
    } else if (targetPoint.y > self.bounds.size.height) {
        targetPoint.y = self.bounds.size.height;
    }
    CAMediaTimingFunction *timingFunction = [CAMediaTimingFunction functionWithControlPoints:
                                             0.1f : 0.9f :0.2f :1.0f];

    [CATransaction begin];
    [CATransaction setValue:[NSNumber numberWithFloat:kDecelerationDuration] forKey:kCATransactionAnimationDuration];
    [CATransaction setAnimationTimingFunction:timingFunction];

    self.sprite.position = targetPoint; 
    [CATransaction commit];

}

This is a very simple example. You may want a better vector-getting mechanism. Also, this only move a visual component (CALayer). You would probably need an UIView object to handle events from the object. In this case, you might want to animate through CALayer, and move the actual UIView object separately. There could be multiple ways of handling the CALayer animation and UIView relocation together.

like image 130
MHC Avatar answered Oct 05 '22 08:10

MHC


Use Core Animation. It's pretty straightforward if you look at the docs for UIView -- create an animation that sets the final position of the view, and specify UIViewAnimationOptionCurveEaseOut as the timing curve. The whole thing will take you just a handful of lines to implement.

like image 45
Caleb Avatar answered Oct 05 '22 08:10

Caleb