在我的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点之间的距离
在标题中:
NSMutableArray *pathPoints;
在初始化时:
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];
解除分配:
[pathPoints release];
关于ios - 如何计算b2body对象的行进距离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20058537/