我在Cocos2d中的侧边滚动有问题。情况是这样的,我有一个精灵,它包含多个其他的精灵,称为动作。用户可以水平来回滑动以滚动多个动作。现在发生的情况是,它非常抖动,似乎滞后,不是一个平滑的滚动,而只是非常起伏。不确定是什么问题,我试着改变动画的时间,但似乎不起作用。
- (void)translateInventoryForSwipe:(int)xTranslationValue {
NSArray* tempArray = [NSArray arrayWithArray:self.slotsCenterCoordinates];
[self.slotsCenterCoordinates removeAllObjects];
for (NSNumber* i in tempArray) {
NSNumber* newXCoordinate = [NSNumber numberWithInt:[i intValue] + xTranslationValue];
[self.slotsCenterCoordinates addObject:newXCoordinate];
}
[self updatePositionOfActionsInInventory];
}此方法从父视图中获取两个触点的增量x。(当前触摸减去以前的触摸)此选项设置滚动视图中所有操作的中心坐标。
- (void)updatePositionOfActionsInInventory {
for (int inventoryCounter = 0; inventoryCounter < self.inventorySize; inventoryCounter++) {
FFAction* action = [self.actions objectAtIndex:inventoryCounter];
if (action != self.actionBeingDragged)
[self placeAction:action atIndex:inventoryCounter];
}
self.tempAction = nil;
}
- (void)placeAction:(FFAction*)action atIndex:(int)index {
const float yCenterCoordinate = self.boundingBox.size.height/2;
NSNumber* xCenterCoordinate = [self.slotsCenterCoordinates objectAtIndex:index];
CGPoint centerPointForActionAtIndex = ccp([xCenterCoordinate floatValue], yCenterCoordinate);
CCAction* updatePositionAction = [CCMoveTo actionWithDuration:0.03f position:centerPointForActionAtIndex];
if ([action.view numberOfRunningActions] == 0 || self.tempAction == action) {
[action.view runAction:updatePositionAction];
[action.view released];
}
}这部分来自处理触摸的父子画面:
CGPoint currentTouch = [self convertTouchToNodeSpace:touch];
CGPoint previousTouch = [touch previousLocationInView:[touch view]];
int translationPoint = currentTouch.x - previousTouch.x;
[self.inventory translateInventoryForSwipe:translationPoint withPoint:currentTouch];然后设置模拟滚动效果的动作坐标。我不确定是什么原因导致了抖动,但如果有人能对这种情况有任何帮助,那就太棒了!
发布于 2013-11-25 04:31:13
假设代码中的所有复杂性都不是必需的,这里有几个方面需要考虑,我将逐一介绍它们。
首先,内存分配的开销很大,而且每次调用translateInventoryForSwipe:时都要进行大量的内存分配。将创建一个全新的NSArray,并重新填充该self.slotsCenterCoordinates。相反,您应该迭代动作精灵,并逐个重新定位它们。
这就引出了第二个方面,那就是使用CCAction来移动精灵。为每个精灵创建一个新的CCAction,由于内存分配的原因再次导致延迟。即使不使用CCAction,也会创建它。此外,动作的使用可能是延迟的主要原因,因为新的动作在前一个动作完成之前不会被接受。一种更好的方法是通过增量直接重新定位精灵,而不是为重新定位指定动作。由于对translateInventoryForSwipe:的调用频率将很高,因此不需要执行该操作即可获得平滑的移动。
您还应该考虑使用float将delta值发送给方法,而不是int。触摸坐标是浮动的,特别是在视网膜设备上,这一点很重要,因为两个像素的距离是0.5f。
基于这些方面,这里有一个固定方法的模板。这未经过测试,因此可能存在错误。此外,我假设action.view是实际的精灵,因为操作是在那里分配的。
- (void)translateInventoryForSwipe:(float)xTranslationValue {
for (FFAction *action in self.actions) {
if (action == self.actionBeingDragged)
continue;
// Position the items manually
float xCoordinate = action.view.position.x + xTranslationValue;
float yCoordinate = self.boundingBox.size.height/2;
action.view.position = ccp(xCoordinate, yCoordinate);
}
}https://stackoverflow.com/questions/19684572
复制相似问题