您的位置:首页 > 移动开发 > Cocos引擎

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOS iPhone cocos2d