cocos2d触摸移动速度

问题描述:

我需要在cocos2d中获得触摸移动速度。任何API?cocos2d触摸移动速度

这样做的最基本的方法就是要做到以下几点:

  1. 当然,注册是一个触摸事件处理程序CCLayer,并实现触摸开始,移动和结束的功能。

  2. 创建您的相关类,2 CGPoint变量来存储CURRENTPREVIOUS触摸位置。还创建2 CCTIme结构来存储CURRENTPREVIOUSLY轮询时间。

  3. 设置计划更新当前时间(我在任何相关类的初始化完成这个

即:。

- (id)init { 
    if((self = [super init])) { 
     [self schedule:@selector(update:)]; 
     timeCURRENT = (ccTime)0; 
    } 
    return self; 
} 

-(void)update:(ccTime)deltaTime { 
    timeCURRENT += deltaTime; 
} 

4日开始触摸开始,使用以下命令将先前和当前变量设置为当前触摸位置:

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { 
touchCURRENT= [touch locationInView: [touch view]]; 
touchPREVIOUS = touchCURRENT; 
timePREVIOUS = timeCURRENT; 
... 

然后,在触摸移动时,设置PREVIOUS到当前,并设置使用相同的代码线的电流如上

-(BOOL)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { 
    touchPREVIOUS = touchCURRENT; 
    touchCURRENT= [touch locationInView: [touch view]]; 
    CGPoint deltaPosition = touchCURRENT - touchPREVIOUS; 
    ccTime deltaTime = timeCURRENT - timePREVIOUS; 
    timePREVIOUS = timeCURRENT; 

速度= deltaPosition /的DeltaTime。

注意CGPoint减法可能无法正常工作,上面做广告,你可能要减去个人会员,他们送入一个CGPoint工厂方法。

+0

非常感谢。它现在有效。顺便说一句,搜索“鱼vs鸟”2周后,它会是真棒! – John 2011-03-23 15:33:30

+0

我的代码在这里:prevPos = curPos; \t curPos = [MainScene locationFromTouches:touches]; \t \t float xDif = prevPos.x - curPos.x; \t float yDif = prevPos.y - curPos.y; \t \t float distance = sqrt(xDif * xDif + yDif * yDif); \t \t ccTime deltaTime = curTime - prevTime; \t prevTime = curTime; \t \t float velocity = distance/deltaTime; – John 2011-03-23 15:34:00

+0

令人兴奋,好听。然而,在附注中,请确保您正确地复制了“鱼”字。鱼的复数是鱼。当涉及多种不同的鱼类时,它只是鱼类。 – 2011-03-23 21:55:24