How to generate an end screen when two images collide?

為{幸葍}努か 提交于 2019-12-02 19:25:40

问题


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 will generate the end screen. How do I make the app detect this collision and then generate an end screen.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5841279/how-to-generate-an-end-screen-when-two-images-collide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!