如何将for循环中的int解析为xcode中的方法



嗨,伙计们,我想做的是创建6个精灵,并将它们均匀地隔开,我编辑了一些从书中得到的代码,但目前我被困在需要将精灵均匀地隔开的部分

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

这将在哪里将所有6个精灵堆叠在一起?我怎么能让它变成这样

    [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中,而它一直是另一种类型?我认为那个结束了。。。

最新更新