Inertial Scrolling

On the iOS, scrolling works in way that feels very natural: when you move, say, a page in Safari, it doesn't stop moving immediately when you lift the finger off the screen. Instead, the page moves on and gets slower over time, coming to a full halt after about a second.

Here is a code snippet that allows you to move objects in a similar way.

// in the init-method: (add the variables as member variables to your class!)
mTouching = NO;         // BOOL
mLastScrollDist = 0.0f; // float
mList = [[MyCoolList alloc] init];  // that is the object you'd want to move
[self addChild:mList];
[mList addEventListener:@selector(onTouch:) atObject:self
// touch event listener:
- (void)onTouch:(SPTouchEvent*)touchEvent
    mTouching = [[touchEvent touchesWithTarget:self andPhase:SPTouchPhaseEnded] count] == 0;
    if (!mTouching) return;
    SPTouch* touch = [[touchEvent touchesWithTarget:self andPhase:SPTouchPhaseMoved] anyObject];
    SPPoint *localPos = [touch locationInSpace:self];
    SPPoint *previousLocalPos = [touch previousLocationInSpace:self];
    mLastScrollDist = previousLocalPos.y - localPos.y;
    mList.y += mLastScrollDist;
// enter frame event listener
- (void)onEnterFrame:(SPEnterFrameEvent *)event
    if (!mTouching)
        float slowDown = 0.98f;
        if (fabsf(mLastScrollDist) < 0.5f)
            slowDown = 0;
        mLastScrollDist *= slowDown;
        mList.y += mLastScrollDist;

Beware that this is not a perfect implementation; i.e. it behaves differently depending on the frame rate. But it should be a good place to start. More information can be found in this forum thread.

  tutorials/intertial_scrolling.txt · Last modified: 2013/03/05 10:19 by
Powered by DokuWiki