具有多个相同对象的 CALayer 数组
我是否正在尝试创建一款不断向用户发射障碍物的游戏?我有一个 NSMutableArray,所以我可以作为一个组访问所有障碍。这是我的代码:
CALayer *obstacle = [[[CALayer alloc] init] autorelease];
UIImage *obstacleImage = [UIImage imageNamed:@"Obstacle.png"];
obstacle.contents = (id)obstacleImage.CGImage;
obstacle.bounds = CGRectMake(0, 0, starImage.size.width/2, starImage.size.width/2);
int xPosition = (arc4random()%(360-0))+0;
obstacle.position = CGPointMake(xPosition, 20);
[self.view.layer addSublayer:obstacle];
[self.obstacleArray addObject:obstacle];
我的问题是:如何访问该数组中的对象?我希望能够访问最新的对象,以便可以为其设置动画。我浏览过 NSMutableArray Class Reference ,但仍然找不到任何东西。我已经尝试过这个:
NSLog(@"%d",[obstacleArray indexOfObject:obstacle]);
但它返回的只是:0。是否有一个我没有看到的简单解决方案?预先感谢您的任何回复。
Am I trying to create a game where an obstacle is constantly fired at the user. I have an NSMutableArray so I can access all the obstacles as a group. Here is my code:
CALayer *obstacle = [[[CALayer alloc] init] autorelease];
UIImage *obstacleImage = [UIImage imageNamed:@"Obstacle.png"];
obstacle.contents = (id)obstacleImage.CGImage;
obstacle.bounds = CGRectMake(0, 0, starImage.size.width/2, starImage.size.width/2);
int xPosition = (arc4random()%(360-0))+0;
obstacle.position = CGPointMake(xPosition, 20);
[self.view.layer addSublayer:obstacle];
[self.obstacleArray addObject:obstacle];
My questions is: How would I access the objects in this array? I want to be able to access the latest object so I can animate it. I have looked through the NSMutableArray Class Reference , but still can't find anything. I have tried this:
NSLog(@"%d",[obstacleArray indexOfObject:obstacle]);
But all it returns is: 0. Is there an easy solution to this problem that I'm just not seeing? Thanks in advance for any responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
[obstacleArray lastObject]
或[obstacleArray objectAtIndex:[obstacleArray count]-1]
获取最后一个对象。您可以在 NSArray 类参考中找到它。 (因为它是 NSMutableArray 的父类)Use
[obstacleArray lastObject]
or[obstacleArray objectAtIndex:[obstacleArray count]-1]
to get the last Object. You can find that in the NSArray Class Reference. (Since it's the parent class of NSMutableArray)