2016-05-14 67 views
-4

我试图在python中使用tkinter创建逼真的引力。重力的作用,但我动画的球不停止。这里是我的代码:Python:停止引力

import tkinter as tk 
import time 

xv=0 
yv=0 
x=0 
y=0 
def move(event=None): 
    global xv,yv, direction 

    if event.char == 'w': 
     yv-=15 
    elif event.char == 'a': 
     xv-=1 
    elif event.char == 'd': 
     xv+=1 
    elif event.char == 's': 
     yv+=1 


m = tk.Tk() 

canvas = tk.Canvas(m) 
canvas.pack(expand=2, fill='both') 
oval_id = canvas.create_oval(0,0,10,10,fill='red') 

canvas.bind_all('<w>', move) 
canvas.bind_all('<a>', move) 
canvas.bind_all('<d>', move) 
canvas.bind_all('<s>', move) 

while 0==0: 
    yv*=0.9 
    xv*=0.9 
    x+=xv 
    y+=yv 
    yv+=1 
    if y > 170: 
     yv=0 
    time.sleep(0.05) 
    canvas.move(oval_id,xv,yv) 
    canvas.update() 

球停止,但当你按w跳,它沉没下来,在屏幕上。我可以在不使用太多代码的情况下将它恢复到170px吗?

+0

从您的变量的名称('xv','yv'),你有速度,加速度不工作。对于一个合理的重力模型来说,你应该只使用加速度。 –

+0

这不是我正在与之合作。问题不是加速度,而是重力停止的事实。 – pajamaman7

回答

1

使用绝对坐标和不断向下的加速度:

yv = 0 
xv = 1 
while True: 
    yv += .5 # .5 is the acceleration 
    x+=xv 
    y+=yv 
    if y > 170: # check that didn't move past the floor 
     y=170  # reset to the floor 
     yv = -yv*.9 # reverse velocity and lose some energy from the bounce 
    time.sleep(0.05) 
    canvas.coords(oval_id,x,y,x+10,y+10) # use absolute coordinates 
    canvas.update() 
+0

谢谢!那工作完美。我修改了一下,因为完成的代码将用于一个平台游戏,但现在它的工作方式就像我想要的那样! – pajamaman7