python - 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)
解决方案
问题是pygame.Rect
s 只能有整数,因为它们的坐标和浮点数会被截断。如果要将浮点值作为速度,则必须将实际位置存储为单独的属性(或两个,如下面的第一个示例),每帧将速度添加到它,然后将新位置分配给矩形。
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
推荐阅读
- javascript - 如何在 React Native 中获取 API 之前保存当前位置的经纬度坐标?
- java - 如何在 Mongodb (Spring) 上编写此聚合查询
- android - Android webview不显示网站的一部分
- ansible - Ansible playbook:打印消息
- powershell - 在 PowerShell 中使用 while 循环和服务重新启动进行网站检查
- c++ -
': 无法从 'const boost::filesystem::path::value_type *' 转换为 'std::string' - java - Android 编程 TCP-Server 连接
- c# - 单元测试通过选择 C# 发布和删除的方法
- javascript - 两个容器之间的自定义形状线,可以像进度条一样改变颜色
- java - 为什么我无法从 Enum 对象类中获取 .values()?