COCOS2DX中实现图层的惯性拖拽
苹果的应用讲究用户体验
有的时候仔细想想
的确,很多细节决定了用户体验
比如说惯性拖动
可以说之前没有任何一家厂商能把触摸惯性拖动做的像苹果的UI那么流畅
这次简单的写一下在Cocos2D中实现图层的惯性拖动
原理是简单模拟物理引擎的计算,通过改变力来改变图层的运动速度,以达到流畅的体验
直接上代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#import "cocos2d.h" @interface DragLayer : CCLayer { BOOL isDragging;//是否正在拖动 CGPoint lastPosition;//上一个时间间隔时的图层位置 CGPoint velocity;//图层移动速度 CGPoint acceleration;//加速度 CGPoint force;//受力 } +(id) dragLayer ; @end #import "DragLayer.h" @implementation DragLayer -(id)init { if((self = [super init])) { // 初始化图层 self.isTouchEnabled = YES; isDragging = NO; lastPosition = CGPointZero; velocity = CGPointZero; acceleration = CGPointZero; force = CGPointZero; // 开启计时器 [self scheduleUpdate]; } return self; } } +(id) dragLayer; { return [[[self alloc] init] autorelease]; } -(void)update:(ccTime)delta { // 如果没有被拖拽,模拟物体惯性 if ( !isDragging ) { CGPoint pos = self.position; // *** 通过在这里改变图层的受力,达到自然的惯性拖拽 *** // // 在这里,只添加一个方向和速度方向相反,大小和速度大小相同的阻力,一次不断减小速度,最终速度为零时,受力为零,物体静止 // force = ccpMult(velocity, -0.1); // 将受力计算为最终物体的移动 acceleration = ccpMult(force,1); velocity = ccpAdd(velocity,acceleration); CGPoint change = ccpMult(velocity,dt); pos = ccpAdd(pos,change); self.position = pos; } // 如果正在拖拽,记录下拖拽时图层的移动速度 else { velocity= ccpSub(self.position,lastPosition); lastPosition= self.position; } } -(void)registerWithTouchDispatcher { [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:1 swallowsTouches:YES]; } -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { // 标记为正在拖拽 isDragging = YES; return YES; } -(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { // 根据触摸点位移改变图层位置 CGPoint a = [[CCDirector sharedDirector] convertToGL:[touch previousLocationInView:touch.view]]; CGPoint b = [[CCDirector sharedDirector] convertToGL:[touch locationInView:touch.view]]; CGPoint change = ccpSub(b,a); self.position = ccpAdd(self.position,change ); return; } -(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // 结束拖拽,标记为未拖拽 isDragging = NO; return; } - (void) dealloc { // in case you have something to dealloc, do it in this method // in this particular example nothing needs to be released. // cocos2d will automatically release all the children (Label) // don't forget to call "super dealloc" [super dealloc]; } @end