from Tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=500, background="green")
canvas.pack()
x0 = 225
y0 = 225
x1 = 275
y1 = 275
speed_x = 2
speed_y = 3
ball = canvas.create_oval(x0,y0,x1,y1,fill="blue", tag='ball')
while True:
canvas.move('ball', speed_x, speed_y)
canvas.after(30)
canvas.update()
if x1 >= 500:
speed_x = -2
if x0 <= 500:
speed_y = -3
if y1 >= 0:
speed_y = 2
if y0 <= 0:
speed_x = 3
x0 += speed_x
x1 += speed_x
y0 += speed_y
y1 += speed_y
mainloop()
我的目标是让球永远在屏幕上反弹。现在,球从右墙反弹,但随后又消失在底壁上。
答案 0 :(得分:0)
您的问题是一个非常简单的逻辑问题
这是你写的:
if x1 >= WIDTH: speed_x = -velocity
if x0 <= WIDTH: speed_y = -(velocity+1)
if y1 > 0: speed_y = velocity
if y0 < 0: speed_x = (velocity+1)
我们想要说的是,如果我们在任何边界条件之外,则沿着适当的分量反转我们的速度。
也许您立即怀疑自己从不检查高度上的y位置,或者您可能会怀疑您是否根据x位置调整了y速度。无论哪种方式,都要怀疑
以下是您按顺序编写的内容
与此逻辑比较:
if x1 >= WIDTH: speed_x = -velocity
if x0 <= 0: speed_x = velocity
if y1 >= HEIGHT: speed_y = -velocity
if y0 <= 0: speed_y = velocity