简体   繁体   中英

Is there a way to detect if a UIView is touching another UIView? Swift 4

I have been developing a scrolling endless runner game (in Swift 4), and I want to detect if the player is touching a block/tile. Currently, I am using this code:

let centerX = Float(UIScreen.main.bounds.size.width) / 2
for i2 in 0...tiles.count-1 {
    if scrollX + centerX > Float(tilePosition[i2][0] - 60) {
        if scrollX + centerX < Float(tilePosition[i2][0] + 60) {
            if Int(player.center.y) > tilePosition[i2][1] - blockFloatings[playerFrame] {
                if Int(player.center.y) < tilePosition[i2][1] + blockFloatings[playerFrame] {
                    while Int(player.center.y) > tilePosition[i2][1] - blockFloatings[playerFrame] {
                        playerGravity = 0
                        player.center.y = player.center.y - CGFloat(1)
                    }
                }
            }
        }
    }
}

The code works, but it won't be accurate enough. I have rounded tiles such as this , and also tiles with a wavy top like this .

Right now, my code assumes the tile is a square, but sometimes it isn't. If the tile isn't a square, like the water, I want it so as you move right or left, the player moves up and down.

If you are going to answer this question, here are some things you would probably need to know about my current code:

centerX - The middle of the screen

tiles - The UIImageView() for the blocks/tiles

scrollX - The scroll in X

tilePosition - An array containing the positions of the blocks/tiles

blockFloatings - The player UIImageView() will be changing images, and each image is a different height. This array contains the numbers at which the player shouldn't fall through the ground (subtracting y-position)

playerFrame - The image ID of the player

player - The UIImageView() representing the player

playerGravity - The variable that states how fast the player should fall down each frame

Edit: You can also answer that there is no way possible.

You could try using:

bool CGRectIntersectsRect(CGRect rect1, CGRect rect2);

by passing the player's frame and the tiles' frame as parameters.

Link to the documentation:

https://developer.apple.com/documentation/coregraphics/1454747-cgrectintersectsrect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM