0

我正在使用 CCNode userData 属性来定义被触摸的精灵是否已经在其上构建了一个节点(使用Ray Wenderlich 的 - 塔防教程)。

我遇到的问题是,对于我接触和构建的每个新精灵位置,以前的位置都不会保留,因为我无法使用我的销售方法出售建立在它上面的建筑物。

将数据保存到通过触摸选择并通过 for 循环由属性定义的单个 CCSprite 的最佳方法是什么?

我已经读过子类化 CCSprite 是一种选择,或者为 userData 创建一个结构等。我试图实现这些策略,但未能成功让它们工作。

具有 sprite 属性的 touch 方法:

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

    for(UITouch *touch in touches){
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    for(CCSprite *tb in self.BuildPositions){
//BuildPositions contains CCSprites from a class defining build positions and contained in a mutable array.
        if(CGRectContainsPoint([tb textureRect],[tb convertToNodeSpace:location ])){

            _selectedBuildPosition = tb;
            [self buildMenuTapped];
      }
    }
  }
}

构建菜单方法:

-(void)buildMenuTapped{

[self removeChild:_buildSelectMenu cleanup:YES];
[self removeChild:_sellBuildingMenu cleanup:YES];

if (_selectedBuildPosition.userData == nil) {

    CCMenuItem *buildOption = [CCMenuItemImage itemWithNormalImage:@"building.png" selectedImage:@"building.png" target:self selector:   @selector(buildOption)];
    buildOption.position = ccpAdd(_selectedBuildPosition.position,ccp(0,40));

    _buildSelectMenu = [CCMenu menuWithItems:BuildOption, nil];
    _buildSelectMenu.position = CGPointZero;
    [self addChild:_buildSelectMenu z:100];

}else{

    [self sellBuildingMenu];
}
}

建立在方法上:

-(void)buildOption{

if([self canBuyBuilding] && !_selectedBuildPosition.userData){

    _playerEssence -= kBUILD_COST;

    _lvl1BuildNodeInstance = [lvl1BuildNode nodeWithTheGame:self location:_selectedBuildPosition.position];
//method as seen in RW tutorial. Generates a lvl1BuildNode class node within the HelloWorldLayer.

    _selectedBuildPosition.userData = (__bridge void*)(_lvl1BuildNodeInstance);

  }
}

销售菜单方法:

-(void)sellBuildingMenu{
[self removeChild:_buildSelectMenu cleanup:YES];
[self removeChild:_sellBuildingMenu cleanup:YES];

CCMenuItem *buildingSell = [CCMenuItemImage itemWithNormalImage:@"sell.png" selectedImage:@"sell.png" target:self selector:@selector(sellBuilding)];
buildingSell.position =  ccpAdd(_selectedBuildPosition.position,ccp(40,0));

_sellBuildingMenu = [CCMenu menuWithItems:buildingSell, nil];
_sellBuildingMenu.position = CGPointZero;
[self addChild:_sellBuildingMenu z:100];
}

销售方式:

-(void)sellBuilding{
    if (_selectedBuildPosition.userData == (__bridge void*)(_lvl1BuildNodeInstance)){

        [self removeChild:_lvl1GemNodeInstance cleanup:YES];

        [_buildings removeObject:_lvl1BuildNodeInstance];

        _playerEssence += kBUILD_COST;

        _selectedBuildPosition.userData = nil;

    }else{
    }
}

感谢您的时间。

4

0 回答 0