1

我已经编写了一个代码来使用 CCLog 显示当释放移动鼠标时精灵的确切位置。下面是 Sprite.mm 类和 ccTouchesEnded 方法(在 HelloWorldLayer.mm 类中)。精灵位置没有更新,输出一直是 x: 0.00 和 y: 0.00。

精灵.mm:

-(id)addSprite:(CCLayer *)parentLayer
                 inWorld:(b2World *)world
{
PhysicsSprite *aSprite = [PhysicsSprite spriteWithFile:@"spriteIm.png"];

aSprite.tag = 1;
[parentLayer addChild:aSprite];

b2BodyDef spriteBodyDef;
spriteBodyDef.userData = aSprite;
spriteBodyDef.type = b2_dynamicBody;
CGSize s = [CCDirector sharedDirector].winSize;
spriteBodyDef.position = [Convert toMeters:ccp(s.width * 0.25,s.height-400)];
b2FixtureDef fixtureDef;
fixtureDef.density = 0.01;
b2CircleShape circleShape;
circleShape.m_radius = aSprite.contentSize.width/2 / PTM_RATIO;
fixtureDef.shape = &circleShape;

spriteBody = world->CreateBody( &spriteBodyDef );
spriteFixture = spriteBody->CreateFixture( &fixtureDef );

[aSprite setPhysicsBody:spriteBody];

return aSprite;
}

ccTouchesEnd:

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

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

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

请帮忙。我已经做了几天了。

4

1 回答 1

0

我终于设法让它工作了。我猜 x:0.00 和 y:0.00 是因为我占据了精灵的位置而不是身体。sprite 是 body 的父对象,因此它在其父对象中给出了它的位置,即 0,0。我是这样理解的。这是我对 ccTouchesEnded 代码所做的更改。

ccTouchesEnd:

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

if (mouseJoint)
{
    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);
                CCLOG(@"the sprite postion is x:%0.2f , y:%0.2f", mySprite.position.x, mySprite.position.y);

            }
        }
    }

    world->DestroyJoint(mouseJoint);
    mouseJoint = NULL;
}
}
于 2012-08-13T14:03:52.080 回答