我最近开始将我的java知识转换为目标c,并开始使用xcode制作应用程序.我确实有一些我很困惑的事情.首先在Java中,当我制作自上而下的游戏并且需要拍摄射弹时,我会这样做:
public class Bullet{
int x,y;
public bullet(double x, double y){
this.x = x;
this.y = y;
}
public void tick(){
//logic goes in here to move bullet
}
}
Run Code Online (Sandbox Code Playgroud)
然后我会有一个带有arraylist的课程:
public class MainClass{
ArrayList<Bullet> bulletlist;
public main(){
//create an arraylist that takes Bullet objects
bulletlist = new ArrayList<Bullet>();
//add a new bullet at the coordinate (100,100)
bulletlist.add(new Bullet(100,100));
}
//gameloop(we'll pretend that this gets called every millisecond or so)
public void gameloop(){
//loop through list
for(int i = 0; i < bulletlist.size(); i++){
//run the method tick() at the current index
bulletlist.get(i).tick();
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以...我的问题是如何将此代码转换为目标c.或者换句话说,我如何创建一个类似于创建类对象的示例中的arraylist,然后最后循环遍历这个并调用循环方法或我在其中创建的任何方法.
小智 7
与Java不同,Objective-C没有泛型.它没有多大意义,因为Objective-C是动态类型的(大多数情况下).取而代之的是,NSMutableArray与NSArray存储的实例NSObject或其亚型(类似于ArrayList<Object>在Java中).
这样的事情应该让你开始.
@interface MainClass()
@property(nonatomic, strong) NSMutableArray *bullets;
@end
@implementation MainClass
- (id)init {
if (self = [super init]) {
self.bullets = [NSMutableArray array];
[self.bullets addObject:[[Bullet alloc] initAtX:100 y:100]];
}
return self;
}
- (void)gameLoop {
[self.bullets makeObjectsPerformSelector:@selector(tick)];
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4160 次 |
| 最近记录: |