我很难让这个工作。基本上,我希望我的敌人精灵追逐我的玩家精灵。此刻,它会沿着对角线移动到屏幕的右下角。
我正在学习python我正在制作游戏而且还是新手,所以如果这是一个非常简单的问题,我会道歉。
相关代码:
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.bitmap = pygame.image.load("ball.bmp")
self.enemy_rect = self.bitmap.get_rect()
self.enemy_rect.topleft = [100, 200]
self.speed = 2
def move_to_player(self, Player):
dx, dy = self.enemy_rect.x - player.player_rect.x, self.enemy_rect.y - player.player_rect.y
dist = math.hypot(dx, dy)
if dist == 0:
dist = 1
else:
dx, dy = dx / dist, dy / dist
self.enemy_rect.x += dx * self.speed
self.enemy_rect.y += dx * self.speed
while 1: # main game loop
enemy.move_to_player(player)
所有代码,用于上下文:
import pygame
import sys
import pygame.locals
import math
pygame.init()
size = width, height = 800, 500
colour = 100, 20, 30 # colour for background
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Test')
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.bitmap = pygame.image.load("ball.bmp")
self.player_rect = self.bitmap.get_rect(
self.player_rect.topleft = [100, 200]
def move(self, x, y):
self.player_rect.centerx += x
self.player_rect.centery += y
def render(self):
screen.blit(self.bitmap, (self.shipRect))
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.bitmap = pygame.image.load("ball.bmp")
self.enemy_rect = self.bitmap.get_rect()
self.enemy_rect.topleft = [100, 200]
self.speed = 2
def move_to_player(self, Player):
dx, dy = self.enemy_rect.x - player.player_rect.x, self.enemy_rect.y - player.player_rect.y
dist = math.hypot(dx, dy)
if dist == 0:
dist = 1
else:
dx, dy = dx / dist, dy / dist
self.enemy_rect.x += dx * self.speed
self.enemy_rect.y += dx * self.speed
player = Player()
enemy = Enemy()
player.player_rect.x = 50
player.player_rect.y = 50
enemy.enemy_rect.x = 500
enemy.enemy_rect.y = 300
while 1: # main game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player.move(0, 5)
if event.key == pygame.K_UP:
player.move(0, -5)
if event.key == pygame.K_LEFT:
player.move(-5, 0)
if event.key == pygame.K_RIGHT:
player.move(5, 0)
if player.player_rect.colliderect(enemy.enemy_rect):
pygame.display.set_caption('Hit!')
screen.fill(colour)
screen.blit(player.bitmap, player.player_rect)
screen.blit(enemy.bitmap, enemy.enemy_rect)
enemy.move_to_player(player)
pygame.display.flip()
答案 0 :(得分:2)
首先,self.enemy_rect.y += dx * self.speed
可能应为self.enemy_rect.y += dy * self.speed
其次,我认为你的数学是向后的,这样你的敌人就会逃跑。我们来试试一个简单的例子:
Player at 0,0; enemy at 2,0.
Expected result if speed = 2: both at 0,0
dx = 2, dy = 0 (before normalizing by hypot)
dx = 1, dy = 0 (after)
New result: player still at 0,0; enemy at 4,0
答案 1 :(得分:0)
这就是我用来做这个......
if PlayerX > AI_X:
AI_X += 3
if PlayerX < AI_X:
AI_X -= 3
if PlayerY > AI_Y:
AI_Y += 3
if PlayerY < AI_Y:
AI_Y -= 3
希望这有帮助!