0

我在我的代码中的两个精灵之间创建了一个weldJoint(参见下面的更新方法),我还创建了一个方法,该方法在释放mouseJoint 时返回精灵的确切位置。我想将精灵的当前位置与 spritePositionRelease 值进行比较,如果 y 值相同而 x 值不同,则销毁weldJoint。请帮忙。

spritePositionRelease:

- (CGPoint)spritePositionRelease    {

for(b2Body *b = mouseJoint->GetBodyB(); b; b=b->GetNext())    {
    if (b->GetUserData() != NULL)
    {
        CCSprite *mySprite = (CCSprite*)b->GetUserData();
        if (mySprite.tag == 1) {
            mySprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
            CGPoint spritePosition = mySprite.position;
            CCLOG(@"the sprite position is x:%0.2f , y:%0.2f", spritePosition.x, spritePosition.y);

            return spritePosition;

        }
    }
}
}

ccTouchesEnd:

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

if (mouseJoint)
{
    [self spritePositionRelease];

    world->DestroyJoint(mouseJoint);
    mouseJoint = NULL;
}
}

更新:

-(void) update: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/

int32 velocityIterations = 8;
int32 positionIterations = 1;

// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);

// using the iterator pos over the set
std::set<BodyPair *>::iterator pos;

for(pos = bodiesForJoints.begin(); pos != bodiesForJoints.end(); ++pos)
{
    b2WeldJoint         *weldJoint;
    b2WeldJointDef      weldJointDef;

    BodyPair            *bodyPair = *pos;
    b2Body              *bodyA = bodyPair->bodyA;
    b2Body              *bodyB = bodyPair->bodyB;

    weldJointDef.Initialize(bodyA,
                            bodyB,
                            bodyA->GetWorldCenter());

    weldJointDef.collideConnected = false;
    weldJoint = (b2WeldJoint*) world->CreateJoint(&weldJointDef);

    // Free the structure we allocated earlier.
    free(bodyPair);

    // Remove the entry from the set.
    bodiesForJoints.erase(pos);
}

}  
4

1 回答 1

0

你确定 mouseJoint->GetBodyB() 总是会返回正确的身体吗?也许你应该检查 mouseJoint->GetBodyA() 到?

无论如何,您的检查将非常简单:

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

if (mouseJoint)
{
   CGPoint releasePoint = [self spritePositionRelease];
   CGPoint touchPoint = [[touches anyObject] locationInView:[[touches anyObject] view]];
   if((releasePoint.y==touchPoint.y) &&(releasePoint.x!=touchPoint.x))
   {
//Destroy weld joint
   }
    world->DestroyJoint(mouseJoint);
    mouseJoint = NULL;
}
}
于 2012-08-15T05:40:07.557 回答