当精灵到达特定位置时破坏焊点

时间:2012-08-14 16:01:49

标签: ios cocos2d-iphone box2d physics box2d-iphone

我在我的代码中创建了两个sprite之间的weldJoint(参见下面的update方法),我还创建了一个方法,当释放mouseJoint时返回精灵的确切位置。我想比较sprite的当前位置和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;

        }
    }
}
}

ccTouchesEnded:

- (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);
}

}  

1 个答案:

答案 0 :(得分:0)

你确定mouseJoint-&gt; GetBodyB()会一直返回正确的身体吗?也许你应该检查mouseJoint-&gt; 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;
}
}