我是pygame的新手,正在尝试开发一个游戏,玩家用箭头键移动,并用鼠标的位置旋转(比如mini miltia)。但我可以旋转球员,但不能移动它。它只显示球员旋转,但不移动
def rot_center(image, rect, angle):
rot_image = pygame.transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center=rect.center)
return rot_image, rot_rect
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_orig = load_image('player.png')
self.image = self.image_orig
self.rect = self.image.get_rect()
self.rect_orig = self.rect
self.mask = pygame.mask.from_surface(self.image)
self.x, self.y = int(pygame.display.Info().current_w / 2), int(pygame.display.Info().current_h / 2)
self.rect.topleft = self.x, self.y
self.health = 100
self.damage_done = 0
self.chspeed_x = 10
self.chspeed_y = 10
self.dir = 0
def rot_aim(self, tx, ty):
self.dir = (math.atan2(self.y - ty, self.x - tx) * 180 / PI)
self.image, self.rect = rot_center(self.image_orig, self.rect_orig, self.dir)
def move(self, dx, dy):
self.chspeed_x = dx
self.chspeed_y = dy
self.x = self.x + self.chspeed_x * math.cos(math.radians(270 - self.dir))
self.y = self.y + self.chspeed_y * math.cos(math.radians(270 - self.dir))
def main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
FPS = 30
paused = False
player = Player()
player_s = pygame.sprite.Group()
player_s.add(player)
while not paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEMOTION:
mousepos = pygame.mouse.get_pos()
mouseX = mousepos[0]
mouseY = mousepos[1]
player.rot_aim(mousepos[1], mousepos[0])
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_UP:
player.move(0, 10)
if event.type == pygame.K_DOWN:
player.move(0, -10)
if event.type == pygame.K_RIGHT:
player.move(10, 0)
if event.type == pygame.K_LEFT:
player.move(-10, 0)
player_s.draw(screen)
clock.tick(FPS)
pygame.display.flip()
旋转或移动播放机后,您没有更新} ,因为^{} 对象存储整数值:
self.rect
。实际上,玩家(self.x
,self.y
)的位置发生了变化。但是由于self.rect
用于绘制玩家,因此该属性必须根据位置进行更新。位置必须为^{此外,还有一个拼写错误。您必须将
event.key
与按钮进行比较,而不是event.type
例如:
if event.type == pygame.K_UP:
无论如何,我建议使用^{} 而不是按钮事件,以实现连续平滑的移动。
最后,在绘制场景之前,通过
screen.fill(0)
清除背景:相关问题 更多 >
编程相关推荐