【问题标题】:Pygame key holding not workingPygame 密钥持有不起作用
【发布时间】:2017-09-02 02:35:08
【问题描述】:
import pygame, sys, 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_r]: self.pos[1]-=s
        if key[pygame.K_f]: 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 = 0.1
    print dt
    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 = 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)

这是我的代码。按 WASDRF 应该在按住键的同时不断移动相机,但不是。它没有。每次我想移动一个像素时,我都必须按下键。有人可以解释为什么拿着钥匙不起作用吗?从我发现的所有其他问题来看,这应该可行。

【问题讨论】:

    标签: python python-2.7 pygame


    【解决方案1】:

    刚刚意识到我的错误,所以我想我会自己发布答案。我将整个其余代码放在偶数 for 循环之后的事件 for 循环中,这意味着它只会在每次发生诸如按键之类的事件时更新一个。我需要取消 sys.exit() 之后的所有内容

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2017-06-17
      • 2015-11-19
      相关资源
      最近更新 更多