我想用pygame在簡單的2D窗口中模擬重力。這是非常簡單的東西(點再次上升和下降),我理解力學,即速度作爲一個向量,y部分在每次穿過主循環和隨後更新位置的過程中始終由代表重力的值g減小點。
這一切都工作正常,但我無法選擇正確的值插入。這一切都是嘗試和錯誤。 在如何確定使用哪些數字以獲得半現實的外觀軌跡方面,是否有一個很好的經驗法則?帶pygame的簡單2D引力;價值準則?
我插一個小例子,下面,與我的問題以下值重要:
window = (640, 480) # pixels
initial_speed = 20 # pixels per update along the y axis
gravity = 0.4 # deduction on initial_speed per update
現在,爲什麼這些數字正好使錯覺工作?我首先嚐試使用我在物理課上學習的公式,幾年前和幾年前,但是,無論是否有單位轉換,模擬都是不正確的。大多數時候,我甚至沒有看到球,但通過試錯工作發現上述值。
感謝您的提前幫助。如果您需要更多信息,只需發表評論,我會盡力強制。
這是最簡單的例子。請注意的Vector2D庫方便地從pygame的網站(follow this link)
#!/usr/bin/env python
import pygame
from pygame.locals import *
from vector2D import Vec2d
pygame.init()
GRAVITY = 0.4
class Dot(pygame.sprite.Sprite):
def __init__(self, screen, img_file, init_position, init_direction, speed):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.speed = Vec2d(speed)
self.base_image = pygame.image.load(img_file).convert_alpha()
self.image = self.base_image
# A vector specifying the Dot's position on the screen
self.pos = Vec2d(init_position)
# The direction is a normalized vector
self.direction = Vec2d(init_direction).normalized()
def blitme(self):
""" Blit the Dot onto the screen that was provided in
the constructor.
"""
self.screen.blit(self.image, self.pos)
def update(self):
self.speed.y -= GRAVITY
displacement = Vec2d(
self.direction.x * self.speed.x,
self.direction.y * self.speed.y
)
self.pos += displacement
def main():
DIMENSION = SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
BG_COLOUR = 0,0,0
# Creating the screen
window = screen = pygame.display.set_mode(
(SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
screen = pygame.display.get_surface()
clock = pygame.time.Clock()
dot = Dot(screen, "my/path/to/dot.jpg", (180, SCREEN_HEIGHT),
(0, -1), (0, 20))
mainloop = True
while mainloop:
# Limit frame speed to 50 FPS
time_passed = clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
# Redraw the background
screen.fill(BG_COLOUR)
dot.update()
dot.blitme()
pygame.display.flip()
if __name__ == '__main__':
main()
選擇一個你想要一個像素表示的單位,然後取實數這些東西的價值和插入他們。 –
@Lattyware:我試過了,但正如我非常簡短地提到,如果我使用數字這樣g = 9.81(或10爲清酒的簡單性),實際上發生在窗口內實際上很少的計算。我試圖分配諸如50px對應於1m等東西,但轉換使它更糟糕。你有什麼建議來規避這個問題?感謝您的幫助順便說一句。非常感謝! – Nebelhom