2016-11-18 95 views
0

時,我該如何使框架變小?我有兩個圖像:球和障礙物。如果球碰到障礙物,那就是比賽結束了。當我打電話給CGRectIntersectsRect

但是因爲我的障礙物和球沒有被塑造成一個矩形,所以它看起來像是在他們互相撞擊之前的比賽。我明白他們的框架實際上確實打了對方。但在遊戲中,我的遊戲轉移功能在它看起來像我的球和障礙物相交之前被調用。

希望能夠找到一些幫助,這樣我可以讓我的兩個圖像真的看起來像他們在我的gameover函數被調用之前碰到對方。

if CGRectIntersectsRect(ball.frame, obstacle.frame) { 
    gameOver() 
} 
+1

可以插頁的矩形使其變小。 https://developer.apple.com/reference/coregraphics/1454218-cgrectinset –

+0

這對我來說是有道理的,但我無法讓它起作用。也許我實施錯了?在我的if語句之前,我聲明瞭新的矩形: CGRectInset(obstacle.frame,2000,2000)。 @JoshHomann這是不正確的? – Frederic

+0

這是正確的,但2000,2000似乎非常大,非常隨意。例如用一個球而不是使用包含該圓的矩形,我會使用足夠小的矩形來包含圓。簡單的三角告訴你,高度和寬度應該是sqrt(2)/ 2或0.707乘以外部矩(sin(45)* radius * 2),所以讓collisionFrame = CGRectInset(ball.frame,(1-0.707)* ball .frame.size.width,(1-0.707)* ball.frame.size.height) –

回答

0
extension CGPoint { 
    func distance(to p: CGPoint) -> CGFloat { 
     return sqrt((p.x - self.x) * (p.x - self.x) + (p.y - self.y) * (p.y - self.y)) 
    } 
} 



extension UIView { 

    func collided(with otherView: UIView) -> Bool { 
     let myRadius = bounds.width/2 
     let hisRadius = otherView.bounds.width/2 

     return self.center.distance(to: otherView.center) <= myRadius + hisRadius 
    } 
} 

現在讀得很好:

if ball.collided(with: obstacle) { 
    gameOver() 
}