我做了一个像游戏一样的太空入侵者,一切都很好,除了我觉得我的敌人我编程移动得太快了。如果我使他们的移动速度低于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)
答案 0 :(得分:1)
问题是pygame.Rect
s只能在它们的坐标和浮点数被截断时才有。如果您希望将浮点值作为速度,则必须将实际位置存储为单独的属性(或者如下面的第一个示例中那样),每帧添加速度,然后将新位置分配给矩形。 / p>
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