How to generate an end screen when two images collide?

前端 未结 2 1509
遥遥无期
遥遥无期 2021-01-26 15:42

how to generate an end screen when two images collide. I am making an app with a stickman you move with a very sensitive acceremeter. SO if it hits these spikes, (UIImages) it w

相关标签:
2条回答
  • 2021-01-26 15:58

    I'm sure you know the rect of the two images because you need to draw them so you can use

    bool CGRectIntersectsRect (
       CGRect rect1,
       CGRect rect2
    );
    

    It returns YES if the two rects have a shared point

    0 讨论(0)
  • 2021-01-26 16:01

    The fact that you haven't declared any rects doesn't matter. You need rects for collision detection. I assume that you at least have x and y coordinates for the stickman and you should have some kind of idea of his height and width. Judging from the question title it seems like you're using images to draw the objects you want to check for collision, so you should know the height and width of the images you're using. If you don't have this info you can't draw the objects in the right place and you certainly can't check for collisions.

    You basically want to use the same rects that you use for drawing the objects.

    Some code examples:

    If your coordinates point to the middle of the stickman you would use something like the following:

    if (CGRectIntersectsRect(CGRectMake(stickman.x-stickman.width/2,
                                        stickman.y-stickman.height/2,
                                        stickman.width,
                                        stickman.height),
                             CGRectMake(spikes.x-spikes.width/2,
                                        spikes.y-spikes.height/2,
                                        spikes.width,
                                        spikes.height))) {
        // Do whatever it is you need to do. For instance:
        [self showEndScreen];
    }
    

    If your coordinates point to the top left corner of your stickman you would use:

    if (CGRectIntersectsRect(CGRectMake(stickman.x,
                                        stickman.y,
                                        stickman.width,
                                        stickman.height),
                             CGRectMake(spikes.x,
                                        spikes.y,
                                        spikes.width,
                                        spikes.height))) {
        // Do whatever it is you need to do. For instance:
        [self showEndScreen];
    }
    

    If I might give you a suggestion, I would suggest storing the coordinates and sizes in a CGRect, so that you don't have to create a new CGRect every time you're checking for collision.

    0 讨论(0)
提交回复
热议问题