How to rotate a CGRect in Swift UI to detect collisions

74 views Asked by At

Im working on this game where you have an airplane and there's falling balls from the sky. So to check for collisions between the airplane and the balls I created rectangles to represent their hitbox.

The checkCollision function worked normally until I tried implementing the rotationAngle the airplane has at the moment, when I do that it stops working completely.

here's my check collisions logic:

private func checkCollisions() {
    let airplaneRect = CGRect(
        x: airplane.x - 10,
        y: airplane.y - 60,
        width: 90,
        height: 30
    )

    for index in 0..<raindrops.count {
        let raindropRect = CGRect(
            x: raindrops[index].xPosition - raindrops[index].size / 2,
            y: raindrops[index].yPosition - raindrops[index].size / 2,
            width: raindrops[index].size,
            height: raindrops[index].size
        )

        if intersects(rect1: airplaneRect, rect2: raindropRect, angle: airplane.rotationAngle) {
            collisionDetected = true
        }
    }
}

private func intersects(rect1: CGRect, rect2: CGRect, angle: Angle) -> Bool {
    let rotatedRect1 = rect1.applying(CGAffineTransform(rotationAngle: CGFloat(angle.radians)))

    return rotatedRect1.intersects(rect2)
}

I don't know why it doesn't work.

0

There are 0 answers