[英]Pong game in tkinter, Check for the ball hitting the vertical paddle
我正在嘗試在python tkinter中實現一個pong游戲。 我在畫布的左側有槳,我想檢測球與該槳的碰撞。 有時球剛剛通過槳,我無法正確檢測到碰撞。 請任何幫助表示贊賞,以下是我使用的沖突檢測代碼,不確定它有什么問題。 我正在嘗試實現的是,如果球的位置在槳葉的頂部和底部之間以及左側和右側之間,則存在碰撞
def hit_paddle(self, pos):
""" pos(left, top, right, bottom)"""
paddle_pos = self.canvas.coords(self.shape)
if ball_pos[1] >= paddle_pos[1] and ball_pos[1] <= paddle_pos[3]:
if ball_pos[2] >= paddle_pos[0] and ball_pos[2] <= paddle_pos[2]:
return True
return False
您的想法是正確的,但是在極少數情況下,球可能會穿過槳。
第一個if語句檢查球和槳的y位置。 如果球的任何部分在paddle_pos[1]
和paddle_pos[3]
之間,則應該返回true。
第二條if語句檢查x位置,並且具有相同的邏輯。 您需要檢查球的左側是否在范圍內,因為那是擊中左側槳的球的一部分。
試用以下代碼:
def hit_paddle(self, pos):
""" pos(left, top, right, bottom)"""
paddle_pos = self.canvas.coords(self.shape)
if ball_pos[3] >= paddle_pos[1] and ball_pos[1] <= paddle_pos[3]:
if ball_pos[0] >= paddle_pos[0] and ball_pos[0] <= paddle_pos[2]:
return True
return False
假設ball_pos[1]
是球的邊界框的左下頂點的y坐標,是否不應該對球的邊界框的右上頂點的y坐標施加約束? 例如,如果球剛好位於槳板的下端,我認為您的代碼不會將其視為命中。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.