Search code examples
swiftcollision-detectionpong

Swift Pong(No SpriteKit): Detect side of paddle that the ball hit


Currently, I am making a pong game in Swift(without SpriteKit) that is one player: the ball can bounce off all sides of the view. After some research, I used this algorithm to detect collisions:

if (rect1.x < rect2.x + rect2.width &&
    rect1.x + rect1.width > rect2.x &&
    rect1.y < rect2.y + rect2.height &&
    rect1.y + rect1.height > rect2.y) {
        // collision detected!
}

This works fine, but how can I detect which side of the paddle that the ball hit?

I need to know this because: if the ball hits the bottom or top side of the paddle, I would multiply the y increment by -1. If the ball hits the left or right side of the paddle, I would multiply the x increment by -1.


Solution

  • I found a decent(but not very good) solution. This function returns true if the ball touches either the left or the right side of the paddle, and false if the ball touches either the top or bottom of the paddle.

    func touchHorizontalPaddle() -> Bool {
        if abs(ball.origin.x + ball.width - paddle.origin.x) < 1 || 
           abs(ball.origin.x - (paddle.origin.x + paddle.width)) < 1 {
            return true
        }
        return false
    }
    

    The main issue with this function is that the "less than 1" part is hardcoded. Thus, if the ball speed is too fast, or the increment is too large, the conditional statement may get messed up. Overall, though, it works pretty well.