我在制作歸位演算法以將敵人移向游戲中的玩家時遇到問題。出于某種原因,該演算法有時會起作用,但是當您四處移動玩家時,即使玩家的 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)
uj5u.com熱心網友回復:
由于pygame.Rect應該代表螢屏上的一個區域,因此一個pygame.Rect物件只能存盤整數資料。
Rect 物件的坐標都是整數。[...]
當運動被添加到矩形的位置時,運動的小數部分會丟失。
如果要以浮點精度存盤物件位置,則必須將物件的位置存盤在單獨的變數中并同步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)
# [...]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/400092.html
