2

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

到目前为止,这是我工作缓慢的情况。

- (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 像素?)

我不能使用 Apple 提供的 UIScrollView 或其他方法。它是一个必须靠自身惯性滚动的对象。谢谢。

4

2 回答 2

5

我通过在场景的更新方法中添加“惯性制动”来实现这种惯性滚动(垂直填充许多精灵以模拟垂直滚动选择的 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
    }
}
于 2015-08-03T07:13:22.830 回答
1

touchesMoved 在您滑动期间多次调用。并且每次调用的两点之间的距离为15-30像素。让滑动持续 0.5 秒,该方法被调用 10 次。速度 Y = 30/0.05 = 600。

也只考虑了最后的“touchesMoved speed”。也许您需要计算平均速度?

于 2013-09-17T10:39:34.410 回答