2012-08-13 51 views
1

我已經編寫了一個代碼來顯示使用CCLog時精靈的位置,當一個鼠標聯合移動它被釋放時。下面是Sprite.mm類和ccTouchesEnded方法(它在HelloWorldLayer.mm類中)。精靈位置不更新,輸出始終爲x:0.00和y:0.00。sprite未更新到正確的位置

Sprite.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; 
} 

ccTouchesEnded:

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

請幫助。我已經呆了幾天了。

+0

這將是更容易得到身體像:B = mouseJoint-> GetBodyB()比遍歷世界上每一個機構。不知道其餘的問題對不起:) – iforce2d 2012-08-13 12:53:49

+0

感謝您的意見。 – newbie 2012-08-13 13:55:59

+0

請發佈您的' - (無效)更新:(ccTime)dt' ..我認爲這就是問題所在。 – Lukman 2012-08-13 13:59:16

回答

0

我終於設法讓它工作。我猜測x:0.00和y:0.00是因爲我採取了精靈的位置而不是身體。精靈是身體的父親,所以它將它的位置放在父母的內部,這是0,0。這是我的理解。以下是我對ccTouchesEnded代碼所做的更改。

ccTouchesEnded:

- (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; 
} 
} 
+0

唯一的麻煩是其他的精靈也在觸摸。這給我一個結論,標籤不是真的有用。有沒有人看到我如何設置或我如何訪問標籤有什麼問題?我看起來沒問題。 – newbie 2012-08-13 14:21:50

+1

因爲所有使用'addSprite:inWorld:'添加的精靈標籤= 1。 – Lukman 2012-08-13 14:41:33

+0

@Lukman:添加精靈僅用於添加一個精靈。另外還有一個標籤= 3的精靈。這個精靈也在響應我在ccTouchesEnded中寫的代碼。我最終在兩個精靈之間創建了一個焊接點。這也可以產生效果嗎?我該如何解決這個問題? – newbie 2012-08-13 15:03:03