簡體   English   中英

如何將in循環中的int解析為xcode中的方法?

[英]how to parse int in a for loop to a method in xcode?

嗨,大家好,我要創建6個精靈,並將它們均勻地隔開,我編輯了從書中得到的一些代碼,但目前停留在需要將精靈均勻地隔開的部分

    [groundNode setPosition:CGPointMake(45, 20)];

這會將所有6個Sprite彼此堆疊在一起? 我怎樣才能使它變成類似

    [groundNode setPosition:CGPointMake(45*x, 20)];

其中x是從for循環中獲取的int。 我的代碼在底部列出。 非常感謝!!

-(id)init{
    self = [super init];
    if(self !=nil){
        for(int x=0;x<6;x++){
            [self createGround];
        }   
    }
    return self;
}

-(void) createGround{
    int randomGround = arc4random()%3+1;
    NSString *groundName = [NSString stringWithFormat:@"ground%d.png", randomGround];
    CCSprite *groundSprite = [CCSprite spriteWithFile:groundName];
    [self addChild:groundSprite];
    [self resetGround:groundSprite];
}

-(void) resetGround:(id)node{
    CGSize screenSize =[CCDirector sharedDirector].winSize;
    CCNode *groundNode = (CCNode*)node;
    [groundNode setPosition:CGPointMake(45, 20)];

}

第一步是構建這些方法以采用offsetIndex參數:

-(void) createGroundWithOffsetIndex: (int) offsetIndex {
-(void) resetGround: (CCNode *) node withOffsetIndex: (int) offsetIndex {

然后,在createGround中,將其傳遞給:

[self resetGround:groundSprite withOffsetIndex: offsetIndex];

並從循環中傳遞它:

for(int x=0;x<6;x++){
  [self createGroundWithOffsetIndex:x];
}       

最后,您知道將要使用的部分代碼(在resetGround:withOffsetIndex:內部):(請注意+1,因為偏移量(按語義)從零開始)

[groundNode setPosition:CGPointMake(45 * offsetIndex+1, 20)];

一些注意事項:

  • 仔細考慮這里需要進行多少次傳遞,然后嘗試考慮一種改進的體系結構:如果要平鋪相同的圖像,也許createGround應該采用CGRect並負責填充那么多區域?

  • 這只是水平的; 我將其作為傳遞CGPoints(或類似的{x,y}結構)作為offsetIndex的練習。

  • 您的投放模式是邊界線。 為什么將其作為id傳遞,然后將其轉換為另一個本地var,而將其作為另一種類型呢? 我想那...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM