iphone - 模拟对象的惯性滚动

标签 iphone ios ipad cocoa-touch

我有一个对象需要拖动并模拟惯性滚动。

这是我目前为止运行缓慢的原因。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];

    self.lastTouch = touchLocation;
    self.lastTimestamp = event.timestamp;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInNode:self];

    // how much it scrolled vertically (it is a table view, no need to scroll horizontally)
    CGFloat deltaY = currentLocation.y - self.lastTouch.y;

    // move the container (that is the object I want to implement the inertial movement)
    // to the correct position
    CGPoint posActual = self.container.position; 
    posActual.y = posActual.y + deltaY;
    [self.container setPosition:posActual];


    // calculate the movement speed
    NSTimeInterval deltaTime = event.timestamp - self.lastTimestamp;
    self.speedY = deltaY / deltaTime;

    self.lastTouch = currentLocation;
    self.lastTimestamp = event.timestamp;

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGFloat tempoDecay = 0.4f;

    CGPoint finalPosition = self.container.position;
    finalPosition.y = finalPosition.y + (self.speedY * tempoDecay);

    // move the object to the final position using easeOut timing...

}

这就是我所看到的:我滑动它。当我抬起手指时,它会加速然后突然停止。我记录了 speedY 值,这些值非常大,比如 720! (每秒 720 像素?)

我无法使用 UIScrollView 或 Apple 提供的其他方法。它是一个必须自行滚动的对象。谢谢。

最佳答案

我通过在场景的更新方法中添加“惯性制动”来实现这种惯性滚动(垂直填充许多 Sprite 的 SKSpriteNode 对象以模拟垂直滚动选择)

// add the variables as member variables to your class , setup with initial values on your init 
  SKSpriteNode *mList // this is the sprite node that will be our scroll object
  mTouching = NO;         // BOOL
  mLastScrollDist = 0.0f; // float

在你的 touchesBegan 中,将 mTouching 更改为 YES ,表示触摸生效..

在你的 touchesMoved 中,计算 mLastScrollDist = previousLocation.y - currentlocation.y ,然后将其添加到 mList 的 y 位置 (mList.y += mLastScrollDist)

在您的 touchesEnded 中,将 mTouching 更改为 NO

最后在场景的更新方法中,计算刹车惯性效果

- (void)update:(NSTimeInterval)currentTime
{
    if (!mTouching)
    {
        float slowDown = 0.98f;

        if (fabsf(mLastScrollDist) < 0.5f)
            slowDown = 0;

        mLastScrollDist *= slowDown;
        mList.y += mLastScrollDist; // mList is the SKSpriteNode list object
    }
}

关于iphone - 模拟对象的惯性滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18846945/

相关文章:

iphone - 禁用除一个 View 之外的所有 View 的用户交互

ios - 将图像保存为 nsdata 到 plist 并接收内存警告

iphone - 这些真的是我最终为 iPhone 编程需要采取的步骤吗?

iphone - sudzC 句柄参数

javascript - 我们如何处理 TVML 的逻辑以及它可以与 UIKit 一起使用吗?

iphone - 引用从中添加 subview 的类

iphone - 你能看出这段代码有什么问题吗?

IOS MusicSequence & MusicPlayer 外部 midi 时钟同步

html - 如何使大尺寸(高分辨率)图像适合所有屏幕尺寸,如何避免它超出屏幕

iphone - 弹出窗口内选择器 View 中的问题