如何找到触摸位置是在box2d的形状内?

时间:2011-08-10 05:35:19

标签: ios4 cocos2d-iphone box2d

请任何人帮助我

我已经在我的项目中创建了边缘。我知道如何检查触摸位置是否在形状内

if (fix->TestPoint(locationWorld))
    {
        CCLOG(@"****touch inside shape***");
    }

但我想创建六边形,我需要在六边形内部创建球并在六边形内移动。

我使用以下代码将球移入六边形内:     b2BodyDef groundBodyDef;     groundBodyDef.position.Set(0,0);     b2Body * groundBody = world-> CreateBody(& groundBodyDef);

int countVal=[pos count];
// Define the ground box shape.
b2PolygonShape groundBox;
int range=[pos count]-2;

CCLOG(@"countVal=%d,range=%d",countVal,range);

for (int i=0; i<=range; i=i+2)
{
    float x1,y1,x2,y2;

    x1=[[pos objectAtIndex:i] floatValue];
    y1=[[pos objectAtIndex:i+1] floatValue];

    if (i==range)
    {
        x2=[[pos objectAtIndex:0] floatValue];
        y2=[[pos objectAtIndex:1] floatValue];

    }
    else 
    {
        x2=[[pos objectAtIndex:i+2] floatValue];
        y2=[[pos objectAtIndex:i+3] floatValue];

    }

            CCLOG(@"x1=%f,y1=%f,x2=%f,y2=%f",x1,y1,x2,y2);

    groundBox.SetAsEdge(b2Vec2(x1/PTM_RATIO,y1/PTM_RATIO),b2Vec2(x2/PTM_RATIO,y2/PTM_RATIO));
    groundBody->CreateFixture(&groundBox, 0);

}

但我不知道如何找到触摸位置是多边形形状。我使用cocos2d与box2d

请任何人帮助我

1 个答案:

答案 0 :(得分:1)

最后我得到了答案:     我正在检查点是否在多边形内:

int pnpoly(int npol, float *xp, float *yp, float x, float y)
{
  int i, j, c = 0;
  for (i = 0, j = npol-1; i < npol; j = i++) 
{
    if ((((yp[i] <= y) && (y < yp[j])) ||
         ((yp[j] <= y) && (y < yp[i]))) &&
        (x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
      c = !c;
  }
  return c;
}