基于Zelle Graphics的find_overlapping碰撞检测实现求反馈
Zelle Graphics中find_overlapping碰撞检测的问题与优化
我正在探索用Zelle Graphics的find_overlapping实现碰撞检测的其他方法,我认为这个函数可以检测对象边界框的接触位置(返回元组)。但目前我的代码里圆形会穿过矩形后才触发程序终止,思路可行但需要微调,希望得到反馈。
原代码
from graphics import * win = GraphWin("game loop", 500, 500, autoflush=False) win.master.attributes('-topmost', True) x=20 y=20 dx=20 play=0 cir1=Circle(Point(x,y),10) cir1.setFill("red") cir1.draw(win) x1=300 x2=310 y1=0 y2=50 rect1=Rectangle(Point(x1,y1),Point(x2,y2)) rect1.setFill("blue") rect1.draw(win) xwidth=win.getWidth() while play==0: for i in range(100): xposition = cir1.getCenter().getX() test1=win.find_overlapping(x1,y1,x2,y2) print("This is the length of test1:",len(test1)) print(test1) if xposition+1>=xwidth or xposition-1<=0: dx=-dx cir1.move(dx, 0) update(15) if len(test1)==2: print("overlap") play=1 break print("game over") win.mainloop()
问题分析
- 碰撞检测时机错误:代码先检测矩形范围内的对象,再移动圆形,导致判断的是移动前的状态,圆形已经穿过矩形一部分后才触发终止。
- 窗口边界判断逻辑有误差:只判断了圆心的位置,没考虑圆形半径,容易出现圆形超出窗口后才反弹的情况。
- 碰撞检测范围固定:始终用矩形的初始边界框检测,没有结合圆形的实时位置做动态检测。
优化后的代码
from graphics import * win = GraphWin("game loop", 500, 500, autoflush=False) win.master.attributes('-topmost', True) x = 20 y = 20 dx = 20 play = 0 cir1 = Circle(Point(x, y), 10) cir1.setFill("red") cir1.draw(win) x1 = 300 x2 = 310 y1 = 0 y2 = 50 rect1 = Rectangle(Point(x1, y1), Point(x2, y2)) rect1.setFill("blue") rect1.draw(win) xwidth = win.getWidth() while play == 0: for i in range(100): xposition = cir1.getCenter().getX() # 结合圆形半径判断窗口边界,提前反弹 if xposition + 10 >= xwidth or xposition - 10 <= 0: dx = -dx # 先移动圆形 cir1.move(dx, 0) update(15) # 获取圆形实时边界框,动态检测碰撞 cir_center = cir1.getCenter() cir_left = cir_center.getX() - 10 cir_right = cir_center.getX() + 10 cir_top = cir_center.getY() - 10 cir_bottom = cir_center.getY() + 10 test1 = win.find_overlapping(cir_left, cir_top, cir_right, cir_bottom) print("This is the length of test1:", len(test1)) print(test1) if len(test1) == 2: print("overlap") play = 1 break print("game over") win.mainloop()
优化说明
- 调整执行顺序:先处理边界反弹,再移动圆形,最后做碰撞检测,确保检测的是圆形移动后的实时位置。
- 动态检测范围:用圆形的实时边界框调用
find_overlapping,精准捕捉碰撞瞬间。 - 修正边界判断:结合圆形半径10判断窗口边界,避免圆形超出窗口后才反弹。
内容的提问来源于stack exchange,提问作者netrate
相关产品推荐
相关产品推荐

