pygame 中将敌人移向角色的问题

Problems with moving an enemy towards a character in pygame

我在制作归巢算法以将敌人移向游戏中的玩家时遇到问题。出于某种原因,该算法有时会起作用,但是当您四处移动玩家时,敌人会到达它刚刚停止的点,即使玩家 x 和 y 变量与敌人 x 和 y 变量之间仍然存在差异(代码应始终适用于敌人)。如果你 运行 代码你就会明白我的意思。

这是我的代码:

import pygame
import sys, os, random
from pygame.locals import *
from pygame import mixer
import math

clock = pygame.time.Clock()

screen_width = 700
screen_height = 700 
screen = pygame.display.set_mode((screen_width, screen_height))

player_rect = pygame.Rect(200, 200, 10, 10)
moving_left = False 
moving_right = False 
moving_down = False 
moving_up = False

hunter_rect = pygame.Rect(500, 500, 48, 60)

player_rect.x = 300 
player_rect.y = 200
while True:
    screen.fill((50, 50, 50))


    #screen.blit(player, (player_rect.x, player_rect.y))
    #screen.blit(hunter, (hunter_rect.x, hunter_rect.y))
    pygame.draw.rect(screen, (255, 255, 255), player_rect)
    pygame.draw.rect(screen, (255, 0, 0), hunter_rect)

    #### getting the change in y and the change in x from enemy to player ###
    ychange = (hunter_rect.y - player_rect.y)/100
    xchange = (hunter_rect.x - player_rect.x)/100   


    hunter_rect.x -= xchange
    hunter_rect.y -= ychange


    if moving_left:
        player_rect.x -= 4
    if moving_right:
        player_rect.x += 4
    if moving_up:
        player_rect.y -= 4
    if moving_down:
        player_rect.y += 4

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
            pygame.quit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_a:
                moving_left = True 
            if event.key == K_d:
                moving_right = True 
            if event.key == K_s:
                moving_down = True
            if event.key == K_w:
                moving_up = True
        if event.type == KEYUP:
            if event.key == K_a:
                moving_left = False 
            if event.key == K_d:
                moving_right = False
            if event.key == K_w:
                moving_up = False 
            if event.key == K_s:
                moving_down = False
    
    pygame.display.update()
    clock.tick(60) 

由于pygame.Rect应该表示屏幕上的一个区域,因此pygame.Rect对象只能存储整数数据。

The coordinates for Rect objects are all integers. [...]

将运动添加到矩形的位置时,运动的小数部分丢失。
如果要以浮点精度存储对象位置,则必须将对象的位置存储在单独的变量中并同步 pygame.Rect 对象。 round坐标并将其分配给矩形的位置(例如.topleft):

hunter_rect = pygame.Rect(500, 500, 48, 60)
hunter_x, hunter_y = hunter_rect.topleft

# [...]
while True:
    # [...]

    hunter_x -= xchange
    hunter_y -= ychange
    hunter_rect.topleft = round(hunter_x), round(hunter_y)

    # [...]