用这3个变量,你可以创建多种不同类型的炮塔,它们可以有着不同的攻击属性,比如长距离重型攻击力,但是慢速攻击的炮塔,或者是渴望快速攻击但是攻击范围近的炮塔.
最后,代码包括了一个draw方法,它在炮塔周围绘制圆圈,用来显示调试目的的炮塔攻击范围.
该到了让玩家添加一些炮塔的时候了!
打开HelloWorldLayer.m文件,做出以下修改:
//At the top of the file: #import "Tower.h" //Add the following methods: -(BOOL)canBuyTower { return YES; } - (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 towerBases) { if( CGRectContainsPoint([tb boundingBox],location) && [self canBuyTower] && !tb.userData) { //We will spend our gold later. Tower * tower = [Tower nodeWithTheGame:self location:tb.position]; [towers addObject:tower]; tb.userData = (__bridge void *)(tower); } } } }
ccTouchesBegan:方法当用户在屏幕任意位置点击时调用.代码然后枚举towerBases数组去检查用户点击的位置是否在炮塔基座中.
但是在炮塔创建前,我们需要检查2件事:
- 用户的金币足够吗?canBuyTower方法将检查用户是否有足够的金币去购买炮塔.对于现在来说,你的玩家拥有无穷的金币,canBuyTowers总是返回YES.
- 玩家是否重叠建造炮塔?如果tb.UserData被设置,则表示该基座位置已经有一个炮塔了,所以你不能再其上建造新的炮塔了!