我正在尝试使用 Pygame 库来编写一个简单的游戏。我编写了一个非常简单的“ 敌人”行为来跟随玩家。
问题出在我运行游戏时,“ 敌人”对象向右移动时移动得更快,而向左移动时则移动得慢。
我已经在寻找任何可能影响功能的数字或运算符。我还跟踪了速度和时间值(用于添加或替代“ 距离”),并且它们没有变化(应该不变)。
import os
import sys
import pygame as py
from pygame.locals import *
# Constantes
w = 500
h = 300
clock = py.time.Clock()
active_surf = py.Surface((500, 30))
active_surf.fill((255, 255, 0))
ground_surf = py.Surface((500, 50))
ground_surf.fill((127, 127, 127))
# Clases
class Robbie(py.sprite.Sprite):
def __init__(self, ):
py.sprite.Sprite.__init__(self)
self.image = py.Surface((30, 30))
self.rect = self.image.get_rect()
self.rect.bottom = 250
self.rect.centerx = 230
self.speed = 0.2
def move(self, keys, time):
if self.rect.left >= 0:
if keys[K_LEFT]:
self.rect.centerx -= self.speed * time
if self.rect.right <= w:
if keys[K_RIGHT]:
self.rect.centerx += self.speed * time
def shoot(self, keys, time):
pass
class Enemy(py.sprite.Sprite):
def __init__(self):
py.sprite.Sprite.__init__(self)
self.image = py.Surface((25, 25))
self.rect = self.image.get_rect()
self.rect.bottom = 250
self.rect.centerx = 260
self.speed = 0.1
def move(self, player, time):
if player.rect.centerx > self.rect.centerx:
self.rect.centerx += self.speed * time
if player.rect.centerx < self.rect.centerx:
self.rect.centerx -= self.speed * time
# Funciones
def img_load(img_name):
img_path = os.path.join((os.path.dirname(__file__)), "Images", (img_name + ".png"))
sprite_obj = py.image.load(img_path).convert_alpha()
return sprite_obj
def main():
screen = py.display.set_mode((w, h))
py.display.set_caption("RobbiShoot")
screen.blit(ground_surf, (0, 250))
player = Robbie()
enemy = Enemy()
while True:
time = clock.tick(60)
keys = py.key.get_pressed()
for events in py.event.get():
if events.type == QUIT:
sys.exit()
screen.blit(active_surf, (0, 220))
player.move(keys, time)
enemy.move(player, time)
screen.blit(player.image, player.rect)
screen.blit(enemy.image, enemy.rect)
py.display.flip()
return 0
if __name__ == '__main__':
py.init()
main()
我认为这可能是一些简单的数学运算,但是如果是那样,我将看不到它。
答案 0 :(得分:1)
这是将浮点值转换为整数值的问题:
def move(self, player, time):
if player.rect.centerx > self.rect.centerx:
self.rect.centerx = (self.rect.centerx + self.speed * time + 0.5)
if player.rect.centerx < self.rect.centerx:
self.rect.centerx = (self.rect.centerx - self.speed * time + 0.5)
或
def move(self, player, time):
if player.rect.centerx > self.rect.centerx:
self.rect.centerx = round(self.rect.centerx + self.speed * time)
if player.rect.centerx < self.rect.centerx:
self.rect.centerx = round(self.rect.centerx - self.speed * time)
请注意,如果将0.1转换为整数值,则其值将大于0,但如果将0.9转换为整数值,其值也将变为0。计算x坐标的浮点结果必须四舍五入为0.5。
在答案代码中,x坐标始终被截断,这导致该位置趋向于左侧。