gpt4 book ai didi

iphone - 具有多个 UIImageView 实例的 iOS CGRectIntersectsRect?

转载 作者:行者123 更新时间:2023-11-29 13:32:22 24 4
gpt4 key购买 nike

我有一个应用程序布局,需要检测图像何时与另一个图像发生碰撞。

在这里,用户通过点击他们想要的位置在屏幕上创建多个“球”,即名为“imgView”的 UIImageView 的同一个实例:

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

UITouch *myTouch = [[event allTouches] anyObject];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
imgView.image = [UIImage imageNamed:@"ball.png"];
[self.view addSubview:imgView];
imgView.center = [myTouch locationInView:self.view];

}

(imgView 在 header 中声明为 UIImageView):

    UIImageView *imgView;

现在,我还有一张名为“员工”的图片。它是一个在屏幕上水平平移的长条。我希望图像“staff”能够检测到它与变量“imgView”或用户放置在屏幕上的球之间的每一次碰撞。因此,用户可以点击屏幕上的 10 个不同位置,“工作人员”应该能够捕捉到每一个位置。

我使用这个由 NSTimer 激活的 CGRectIntersectsRect 代码:

-(void)checkCollision {
if( CGRectIntersectsRect(staff.frame,imgView.frame)) {
[self playSound];
}
}

但是,交集只能通过最后一个实例或用户创建的“球”来检测。工作人员对这一点使用react,但对其余部分持平淡态度。非常感谢任何帮助修复我的代码以检测所有实例的帮助。

最佳答案

每次您创建一个新球时,您都会覆盖您的 imgView 实例变量。因此,您的 checkCollision 方法只能看到 imgView 的最新值,即最后创建的球。

相反,您可以在 NSArray 中跟踪屏幕上的每个球,然后检查该数组中每个元素的碰撞。为此,将您的 imgView 实例变量替换为:

NSMutableArray *imgViews

然后,在早期的某个时候,在 viewDidLoad 中初始化数组:

 imgViews = [[NSMutableArray alloc] init]

-touchesEnded:withEvent: 中将新的 UIImageView 添加到数组中:

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

UITouch *myTouch = [[event allTouches] anyObject];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
imgView.image = [UIImage imageNamed:@"ball.png"];
[self.view addSubview:imgView];
imgView.center = [myTouch locationInView:self.view];
[imgViews addObject:imgView]
}

最后,在 checkCollision 中遍历您的数组并对每个元素执行检查

 - (void)checkCollision {
for (UIImageView *imgView in imgViews) {
if( CGRectIntersectsRect(staff.frame,imgView.frame)) {
[self playSound];
}
}

关于iphone - 具有多个 UIImageView 实例的 iOS CGRectIntersectsRect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11535798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com