我一直在尝试按照这个旧的 youtube 教程学习如何使用 pygame 在 Python 中创建游戏。我遇到了一个树桩,我无法让按键 Action 正常工作。我一直关注的教程:https://www.youtube.com/watch?v=g4E9iq0BixA&t=228s
我按 w, a, s, d... 但屏幕没有任何反应
import pygame
import sys
# import math
class Cam:
def __init__(self, pos=(0, 0, 0), rot=(0, 0)):
self.pos = list(pos)
self.rot = list(rot)
def update(self, dt, key):
s = dt * 10
if key[pygame.K_q]: self.pos[1] += s
if key[pygame.K_e]: self.pos[1] -= s
if key[pygame.K_w]: self.pos[2] += s
if key[pygame.K_s]: self.pos[2] -= s
if key[pygame.K_a]: self.pos[0] -= s
if key[pygame.K_d]: self.pos[0] += s
pygame.init()
w, h = 400, 400; cx, cy = w//2, h//2
screen = pygame.display.set_mode((w, h))
clock = pygame.time.Clock()
verts = (-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)
edges = (0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)
cam = Cam((0, 0, -5))
while True:
dt = clock.tick()/1000
for event in pygame.event.get():
if event.type == pygame.QUIT: pygame.quit(); sys.exit()
screen.fill((255, 255, 255))
for edge in edges:
points = []
for x, y, z in (verts[edge[0]], verts[edge[1]]):
x -= cam.pos[0]
y -= cam.pos[1]
z -= cam.pos[2]
f = 200/z
x, y = x*f, y*f
points += [(cx + int(x), cy + int(y))]
pygame.draw.line(screen, (0, 0, 0,), points[0], points[1], 1)
pygame.display.flip()
key = pygame.key.get_pressed()
cam.update(dt, key)
请您参考如下方法:
当为真时:
dt = clock.tick()/1000
问题可能出在这里。如果调试代码并查看存储在 dt 中的时钟滴答值,您会发现该值为 0。因此,当您按下键盘上的某个键时,它不会执行任何操作,因为
s = dt*10 当 dt:= 0 --> s= 0.
我的解决方案是定义一个静态值来模拟试图从时钟滴答中获取的 fps。定义一个低于 000 的值,例如:
当为真时:
**dt = .0009**
那会起作用的。 (:
