我正在尝试根据我在python中的计算来制作pygame中垂直弹簧力的动画/模拟。 该代码似乎可以正常工作,但是它不是很平滑,并且球移出了“画布”。感谢您的帮助:)
(我们应该使用Euler-Cromers方法,但是在动画中它并不那么重要)
我正在用Mu编写动画,
] 1
这是我的代码:
from pygame import *
HEIGHT = 600
WIDTH = 400
COLORS = {
'red': (255, 0, 0),
'green': (0, 255, 0),
'blue': (0,0,255),
'white': (255, 255, 255),
'black': (0,0,0)
}
class Ball:
radius = 20
color = COLORS['red']
x = WIDTH//2
y = HEIGHT//2
speed_y = 1
time1 = 0
time2 = 0
g = 0.981
kF = 10 #N/m
kL = 0.5
m = 1 #kg
def draw(self):
screen.draw.filled_circle((self.x, self.y+300), self.radius, self.color)
def update(self):
self.time2 = time.get_ticks()
dt = (self.time2 - self.time1)/1000
self.time1 = self.time2
self.a = self.g - (self.kL / self.m) * self.speed_y - (self.kF / self.m) * self.y
self.speed_y = self.speed_y + self.a * dt
self.y += int(dt * self.speed_y)
ball1 = Ball()
def draw():
screen.clear()
ball1.draw()
def update():
ball1.update()