开发者

Collision detection using mulitple subviews within a moving view

开发者 https://www.devze.com 2023-01-07 13:39 出处:网络
I am working on a game in OBJ C that has a ball view and a stage view. The stage view has 4 subviews. All views are UIImageViews. I have a method for collision detection that is working. I would like

I am working on a game in OBJ C that has a ball view and a stage view. The stage view has 4 subviews. All views are UIImageViews. I have a method for collision detection that is working. I would like to expand it to more than 4 subviews without simply creating more lines of code. Looking at the code below, is there a way to simplify this into loops instead. Thanks!

// convert each square to be relevant to ball's superview in order to collision detect
CGRect square_01Frame = [ball.superview convertRect:square_01.frame fromView:square_01.superview];
CGRect square_02Frame = [ball.superview convertRect:square_02.frame fromView:square_02.superview];
CGRect square_03Frame = [ball.superview convertRect:square_03.frame fromView:square_03.superview];
CGRect square_04Frame = [ball.superview con开发者_StackOverflow中文版vertRect:square_04.frame fromView:square_04.superview];

// convert CGRects to NSStrings for storage in square_frames array
NSString *square_01FrameString = NSStringFromCGRect(square_01Frame);
NSString *square_02FrameString = NSStringFromCGRect(square_02Frame);
NSString *square_03FrameString = NSStringFromCGRect(square_03Frame);
NSString *square_04FrameString = NSStringFromCGRect(square_04Frame);    

// load array of NSStrings
[square_frames replaceObjectAtIndex:0 withObject:square_01FrameString];
[square_frames replaceObjectAtIndex:1 withObject:square_02FrameString];
[square_frames replaceObjectAtIndex:2 withObject:square_03FrameString];
[square_frames replaceObjectAtIndex:3 withObject:square_04FrameString];

// create a for loop
for (int i=0; i<4; i++) { // 4 squares
    // create test frame
    CGRect test_frame = CGRectFromString([square_frames objectAtIndex:i]);
    if (CGRectIntersectsRect(test_frame,ball.frame)) { // collision detection
        // do something
    }
}


Well, I would do a number of things.

First, I would create a ball "model", just an NSObject subclass to represent the Ball. Probably, that would have a property "location" or something, which is the CGRect.

Then, your current view could have an array of ball objects on the screen, and just loop through them.

Overall, though, I don't think using UIView's rects is the best way to manage collision detection. I think you'd be better off defining that in some other way, and then simply updating the UI accordingly.

Generally, it's not a good idea to rely on your UI implementation for game design. It makes it hard to change (as you note in your question).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号