我正在尝试使用 PyGame 在 python 中创建一个跑步游戏。我熟悉了矩形,并且正在尝试使用它们,但不知道为什么我的敌人角色没有像我希望的那样移动。不过,主角还是有用的:D。有人可以帮我吗?
import pygame
from sys import exit
pygame.init()
WIDTH = 800
HEIGHT = 535
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Nightcrawler")
clock = pygame.time.Clock()
text_font = pygame.font.Font(size=50)
sky = pygame.image.load("10.png").convert_alpha()
ground = pygame.image.load("Ground.png").convert_alpha()
enemy = pygame.image.load("gun.png").convert_alpha()
player = pygame.image.load("detective.png").convert_alpha()
playerRect = player.get_rect(midbottom=(80, 479))
enemyRect = enemy.get_rect(midbottom=(650, 479))
player_rate_X = 0.0
enemy_perimeter = 101
enemy_rate = -0.8
text_surface = text_font.render("NIGHTCRAWLER", False, (255, 255, 255))
def enemy_display(rect) -> None:
screen.blit(enemy, rect)
def player_display(rect) -> None:
screen.blit(player, rect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_rate_X = -1.2
if event.key == pygame.K_RIGHT:
player_rate_X = 1.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_rate_X = 0
if enemyRect.left < 550:
enemy_rate = -enemy_rate
elif enemyRect.right > 0:
enemy_rate = -enemy_rate
playerRect.right += player_rate_X
enemyRect.right += enemy_rate
screen.blit(sky, (0, 0))
screen.blit(ground, (0, 450))
screen.blit(text_surface, (10, 10))
enemy_display(enemyRect)
player_display(playerRect)
pygame.display.update() # it updates everything we displayed above it
clock.tick(60)
我希望我的敌人在某个周长内不断移动,我没有使用矩形来做到这一点,但我想使用矩形来做到这一点
主要问题在于这部分代码:
if enemyRect.left < 550:
enemy_rate = -enemy_rate
elif enemyRect.right > 0:
enemy_rate = -enemy_rate
基本上,敌人正在移动,但它在每一帧上来回移动,因为
enemyRect.right
始终大于 0,因此它在每一帧上都会改变方向。
要解决此问题,请调整这些值。如果您希望敌人继续在屏幕上移动(如果需要,调整
0
和 800
):
if enemyRect.left < 0:
enemy_rate = -enemy_rate
elif enemyRect.right > 800:
enemy_rate = -enemy_rate
补充说明:
if enemyRect.left < 0:
enemy_rate = -enemy_rate
enemyRect.left = 0
elif enemyRect.right > 800:
enemy_rate = -enemy_rate
enemyRect.right = 800
for event ...
循环内以避免意外行为。