2012-03-08 27 views
0

我有一個cocos2d遊戲,在場景中放置一個名爲GameplayLayer的CCLayer。這裏是層的初始化代碼:cocos2d中的調試標籤y值是關閉的

- (id)initWithScene1BackgroundLayer:(Scene1BackgroundLayer *)scene5UILayer { 
    if ((self = [super init])) { 
     uiLayer = scene5UILayer; 
     startTime = CACurrentMediaTime(); 
     [self scheduleUpdate]; 
     self.isAccelerometerEnabled = YES; 
     //chipmunk 
     [self createSpace]; 
     [self createGround]; 
     mouse = cpMouseNew(space); 
     self.isTouchEnabled = YES; 

     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 
      [[CCSpriteFrameCache sharedSpriteFrameCache] 
      addSpriteFramesWithFile:@"escapesceneatlas.plist"]; 
      sceneSpriteBatchNode = [CCSpriteBatchNode 
            batchNodeWithFile:@"escapesceneatlas.png"]; 
      hopper = [[[CPHopper alloc] initWithLocation:ccp(200,200) space:space groundBody:groundBody] autorelease]; 
     } else { 
      [[CCSpriteFrameCache sharedSpriteFrameCache] 
      addSpriteFramesWithFile:@"escapesceneatlas.plist"]; 
      sceneSpriteBatchNode = [CCSpriteBatchNode 
            batchNodeWithFile:@"escapesceneatlas.png"]; 
      //Viking became hopper and starts at bottom 
      hopper = [[[CPHopper alloc] initWithLocation:ccp(100,100) space:space groundBody:groundBody] autorelease]; 

      //An enemy robot called JJ1 also starts at bottom 
      genericBody = [[[CPGenericBody alloc] initWithLocation:ccp(210,200) space:space groundBody:groundBody] autorelease]; 

      //add the batchnode to layer 
      [self addChild:sceneSpriteBatchNode z:0]; 
     } 

     [self addLabel]; 

     [sceneSpriteBatchNode addChild:hopper z:2]; 
     [sceneSpriteBatchNode addChild:genericBody z:2]; 

    } 

    return self; 
} 

的addLabel方法調用料斗類這樣的debugLabel:

-(void)addLabel{ 
//set debuglabel 
CCLabelBMFont *debugLabel=[CCLabelBMFont labelWithString:@"NoneNone" fntFile:@"SpaceVikingFont.fnt"]; 
[self addChild:debugLabel]; 
[hopper setMyDebugLabel:debugLabel];  

}

然後在料斗類的debugLabel代碼是:

-(void)setDebugLabelTextAndPosition { 
CGPoint newPosition = [self position]; 
NSString *labelString = [NSString stringWithFormat:@"X: %.2f \n Y:%d \n", newPosition.x, newPosition.y]; 

[myDebugLabel setString: [labelString stringByAppendingString:@" tracking..."]]; 

float yOffset = screenSize.height * 0.195f; 
newPosition = ccp(newPosition.x,newPosition.y+yOffset); 
[myDebugLabel setPosition:newPosition]; 

}

出於某種原因,當我運行它的X值是好的,它的值似乎是合理的,它始於100,但y值約爲1,567,385,然後如果我移動料斗它會變成35,633,753並不斷變化爲龐大的隨機數。看起來非常不穩定。

這是爲什麼?

回答

0

調試標籤代碼中存在簡單的錯字。您正在將浮點數格式化爲只給出垃圾結果的整數。由於stringWithFormat函數不會隱式地將float轉換爲int,而只是將float的位表示形式解釋爲整數。

更詳細的解釋給出here

所以這

NSString *labelString = [NSString stringWithFormat:@"X: %.2f \n Y:%d \n", newPosition.x, newPosition.y]; 

應該

NSString *labelString = [NSString stringWithFormat:@"X: %.2f \n Y:%.2f \n", newPosition.x, newPosition.y]; 

+0

謝謝,你打敗了我約5小時:)我剛開始NSLogging直接sprite.position.x&y,並看到值很好......只是修復它。謝謝! – marciokoko 2012-03-09 15:53:35