如何计算b2body对象的行程距离

时间:2013-11-18 21:42:17

标签: ios cocos2d-iphone box2d

在我的cocos2d项目中,我在游戏板上有游戏筹码。我使用b2MouseJoint将这个芯片移动到板上。 要移动芯片我使用以下代码

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

        if (_mouseJoint == NULL) return;

        UITouch *myTouch = [touches anyObject];
        CGPoint location = [myTouch locationInView:[myTouch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];
        b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
        _mouseJoint->SetTarget(locationWorld);


}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

        if (_mouseJoint != NULL) return;
        UITouch* touch = [touches anyObject];
        CGPoint startPoint = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
        b2Vec2 locationWorld = b2Vec2(startPoint.x/PTM_RATIO, startPoint.y/PTM_RATIO);
        _touchedBody = [self getBodyAtLocation:locationWorld];

            if(_touchedBody != NULL)
            {
                b2MouseJointDef md;
                md.bodyA = _groundBody;
                md.bodyB = _touchedBody;
                md.target = locationWorld;
                md.collideConnected = true;
                md.frequencyHz = 4.0f;
                md.maxForce = 900000.0f * _touchedBody->GetMass();
                _mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md);
                _touchedBody->SetAwake(true);

            }         


  }

所以,我需要计算我的_touchedBody的行程距离。请帮我。

2 个答案:

答案 0 :(得分:2)

只需在调用ccTouchesBegan时存储对象的位置,然后在ccTouchesMoved完成后使用最终位置来计算差异。

答案 1 :(得分:1)

它不仅会计算2点之间的距离

标题中的

NSMutableArray *pathPoints;

在init上:

pathPoints = [[[NSMutableArray alloc] init] retain];

ccTouchesBegan:

[pathPoints addObject:[NSValue valueWithCGPoint:startPoint]];

ccTouchesMoved:

[pathPoints addObject:[NSValue valueWithCGPoint:location]];

ccTouchesEnded:

[pathPoints addObject:[NSValue valueWithCGPoint:location]];

CGPoint prevPoint = CGPointZero;
float distanceOfTravel = 0;
for(NSValue *v in pathPoints)
{
    if(CGPointEqualToPoint(prevPoint, CGPointZero))
    {
        prevPoint = [v CGPointValue];
        continue;
    }

    CGPoint curPoint = [v CGPointValue];
    distanceOfTravel += ccpDistance(prevPoint, curPoint);
}
NSLog(@"Distance:%f",distanceOfTravel);
[pathPoints removeAllObjects];

的dealloc:

[pathPoints release];