This shows you the differences between two versions of the page.
Previous revision | |||
— | tutorials:intertial_scrolling [2013/03/05 10:19] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Inertial Scrolling ====== | ||
+ | On the iOS, scrolling works in way that feels very natural: when you move, say, a page in Safari, it doesn' | ||
+ | |||
+ | Here is a code snippet that allows you to move objects in a similar way. | ||
+ | |||
+ | <code objc> | ||
+ | // in the init-method: | ||
+ | mTouching = NO; // BOOL | ||
+ | mLastScrollDist = 0.0f; // float | ||
+ | mList = [[MyCoolList alloc] init]; | ||
+ | [self addChild: | ||
+ | [mList addEventListener: | ||
+ | | ||
+ | |||
+ | // touch event listener: | ||
+ | - (void)onTouch: | ||
+ | { | ||
+ | mTouching = [[touchEvent touchesWithTarget: | ||
+ | if (!mTouching) return; | ||
+ | |||
+ | SPTouch* touch = [[touchEvent touchesWithTarget: | ||
+ | SPPoint *localPos = [touch locationInSpace: | ||
+ | SPPoint *previousLocalPos = [touch previousLocationInSpace: | ||
+ | |||
+ | mLastScrollDist = previousLocalPos.y - localPos.y; | ||
+ | mList.y += mLastScrollDist; | ||
+ | } | ||
+ | |||
+ | // enter frame event listener | ||
+ | - (void)onEnterFrame: | ||
+ | { | ||
+ | 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; |