2016-05-14 5 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

ありがとう!それは完璧に働いた。完成したコードはplatformerゲームのために少し修正しましたが、今はそれが欲しいのと同じように動作します! – pajamaman7

関連する問題