我正在创建一个项目,其中有一个随机的Box2d bodies。现在,在绘制方法中,用户在TouchesMoved的基础上绘制了一条,需要使用Box2d 的RayCasting方法来检查该行与Box2D体之间的交集<代码>E 211。
在我的绘图方法中,我使用了以下代码
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主体内的点时,回调并不表示该行相交。我做错什么了??
发布于 2012-01-03 16:47:09
你在画一条线还是一条曲线?对于一行,我假设您只使用检测到的第一点和最后一点。对于曲线,使用检测到的所有点形成正在绘制的曲线。
如果你在画一条曲线,那么你认为我理解这个问题。您正在使用触摸系统检测到的连续点计算相交线。这些连续点彼此非常接近,这会产生很小的射线投射,而可能发生的情况是,你可能会在球内有一个起点和终点,这可能会产生负碰撞。
如果目标是检测您是否正在触摸球,我建议使用在触摸下面维护的传感器,然后在更新方法中检查与此代码的冲突:
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等效的内容。
https://stackoverflow.com/questions/8713023
复制相似问题