Box2D中的RayCasting?

问题描述 投票:0回答:2

我正在创建一个项目,其中我有随机的Box2d机构。现在我在DRAW方法中根据用户的TouchesMoved绘制一条线。我需要使用Box2d的RayCasting方法来检查该线与Box2D体之间的交叉点。

我在我的Draw方法中使用以下代码

for(int i = 0; i < [pointTouches count]; i+=2)
{
    CGPoint startPoint = CGPointFromString([pointTouches objectAtIndex:i]);

    CGPoint endPoint = CGPointFromString([pointTouches objectAtIndex:i+1]);

    ccDrawLine(startPoint, endPoint);

    b2Vec2 start=[self toMeters:startPoint];

    b2Vec2 end=[self toMeters:endPoint];

    [self checkIntersectionbtw:start:end];
}

-(void)checkIntersectionbtw:(b2Vec2)point1:(b2Vec2)point2
{
    RaysCastCallback callback;

world->RayCast(&callback, point1,point2);

if (callback.m_fixture)
{
    NSLog(@"intersected");
    checkPoint = true;
}
}

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

    UITouch *myTouch = [touches anyObject];

    CGPoint currentTouchArea = [myTouch locationInView:[myTouch view]];
    CGPoint lastTouchArea = [myTouch previousLocationInView:[myTouch view]];

    currentTouchArea = [[CCDirector sharedDirector] convertToGL:currentTouchArea];
    lastTouchArea = [[CCDirector sharedDirector] convertToGL:lastTouchArea];

    [pointTouches addObject:NSStringFromCGPoint(currentTouchArea)];
    [pointTouches addObject:NSStringFromCGPoint(lastTouchArea)];


}

但回调仅在绘制的线完全通过实体时告诉交叉点。当用户从外面的某个点开始并将该点留在box2d体内时,回调并不表示该线相交。我可能做错了什么?

ios cocos2d-iphone box2d raytracing
2个回答
0
投票

你画的是一条线还是一条曲线?对于一条线,我假设您只使用检测到的第一个点和最后一个点。对于曲线,您可以使用检测到的所有点来形成您正在绘制的曲线。

如果你画一条曲线,那么我想我明白了这个问题。您正在使用触摸系统检测到的连续点计算交叉线。这些连续的点彼此非常接近,这使得非常小的光线投射,并且可能发生的是你可能正在投射具有球内的起点和终点的线,这可能发出负面碰撞。

如果目标是检测您是否正在接触球,我建议使用触摸下保持的传感器,然后在更新方法中检查与此代码的碰撞:

for (b2ContactEdge* ce = sensorbody->GetContactList(); ce; ce = ce->next)
{   
    b2Contact* c = ce->contact;

    if(c->IsTouching())
    {
         const b2Body* bodyA = c->GetFixtureA()->GetBody();
         const b2Body* bodyB = c->GetFixtureB()->GetBody();

         const b2Body* ballBody = (bodyA == sensorbody)?bodyB:bodyA;

         ...


    }
}

如果你真的想使用光线投射,那么我建议保存一些连续的点并用它们制作一个矢量,以避免小射线投射。

编辑:对不起,我写的例子是用C ++编写的,但你应该能找到Objective-C的等价文件。


0
投票

Box2D的光线投射忽略它们击中的任何“背面”边缘,因此如果光线在灯具内部开始,则该灯具将被忽略。最简单的方法是在两个方向上投射相同的光线。

© www.soinside.com 2019 - 2024. All rights reserved.