首页 > 解决方案 > Pygame:让事情比1慢

问题描述

我做了一个类似 Space Invaders 的小游戏,一切都很好,除了我觉得我编程的敌人移动得太快了。如果我将它们的移动速度设置为低于 1,例如 0.5,它们甚至都不会移动。有没有办法可以让运动更慢?

这是我的敌方单位的代码:

import math


WINDOW = pygame.display.set_mode((800, 900))


class Enemy (pygame.sprite.Sprite):

    def __init__(self):
        super(). __init__ ()
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((20,20))
        self.image.fill((255,0,0))
        pygame.draw.circle(self.image,(COLOUR4), (10,10),10)
        self.rect=self.image.get_rect()
        self.rect.center=(0,0)
        self.dx=2
        self.dy=1

    def update(self):
        self.rect.centery += self.dy


for i in range (100):
    enemy = Enemy()
    enemy.rect.x=random.randrange(750)
    enemy.rect.y=random.randrange(100)
    enemy_list.add(enemy)
    all_sprites_list.add(enemy)

标签: pythonpygame

解决方案


问题是pygame.Rects 只能有整数,因为它们的坐标和浮点数会被截断。如果要将浮点值作为速度,则必须将实际位置存储为单独的属性(或两个,如下面的第一个示例),每帧将速度添加到它,然后将新位置分配给矩形。

class Enemy(pygame.sprite.Sprite):

    def __init__(self, pos):  # You can pass the position as a tuple, list or vector.
        super().__init__()
        self.image = pygame.Surface((20, 20))
        self.image.fill((255, 0, 0))
        pygame.draw.circle(self.image, (COLOUR4), (10, 10), 10)
        # The actual position of the sprite.
        self.pos_x = pos[0]
        self.pos_y = pos[1]
        # The rect serves as the blit position and for collision detection.
        # You can pass the center position as an argument.
        self.rect = self.image.get_rect(center=(self.pos_x, self.pos_y))
        self.dx = 2
        self.dy = 1

    def update(self):
        self.pos_x += self.dx
        self.pos_y += self.dy
        self.rect.center = (self.pos_x, self.pos_y)

我推荐使用vectors,因为它们更加通用和简洁。

from pygame.math import Vector2

class Enemy(pygame.sprite.Sprite):

    def __init__(self, pos):
        # ...
        self.pos = Vector2(pos)
        self.velocity = Vector2(2, 1)

    def update(self):
        self.pos += self.velocity
        self.rect.center = self.pos

推荐阅读