cocods2d实现图层的简单拖拽
2013-09-14 18:52
447 查看
#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
相关文章推荐
- 【10】coco2d-x CCTextFieldTTF最简单的方法实现密码登陆“*”
- 在Cocos2d中实现图层的简单惯性拖拽
- 拖拽系列一、JavaScript实现简单的拖拽效果
- (转)从零实现3D图像引擎:(2)画2D直线不简单
- 今天开始做战斗,回合制战斗代码实现第一篇,从头开始,简单的2d回合制游戏
- js拖拽之一:实现简单的元素拖拽
- [NGUI]基于UIDragDropItem脚本实现简单的控件拖拽
- HTML5简单的拖拽实现
- ArcGIS api for javascript+jquery实现简单的图层控制切换
- html5实现拖放以及mouse事件实现简单拖拽
- JS实现简单拖拽效果
- Unity UGUI 实现简单拖拽功能
- 【转载】从零实现3D图像引擎:(2)画2D直线不简单
- javascript实现 图层拖拽
- 使用js实现的简单拖拽效果
- JavaScript拖拽实现(附注释),最经典!最简单!短小精悍!
- JavaScript 拖拽实现(附注释),最经典简单短小精悍!
- vuejs2.0运用原生js实现简单的拖拽元素功能
- WinForm实现简单的拖拽功能(C#)
- 实现简单的鼠标拖拽事件