Python 让敌人的精灵向玩家移动

Python 让敌人的精灵向玩家移动,python,class,module,pygame,Python,Class,Module,Pygame,到目前为止,敌人的精灵只是在轴上产卵,并与玩家一起“移动”,这实际上是一个滚动背景,我希望敌人只沿着X轴移动,这样就不会破坏沉浸感 我还想让精灵“脱离地图”产卵,每当地图向他们滚动时,他们就会向玩家设定的X轴移动?我认为这会使事情简单化,但这不是目前真正的问题 我试图为该运动工作的当前代码是: def move_towards_player(self, player): # Find direction vector (dx, dy) between enemy and play

到目前为止,敌人的精灵只是在轴上产卵,并与玩家一起“移动”,这实际上是一个滚动背景,我希望敌人只沿着X轴移动,这样就不会破坏沉浸感

我还想让精灵“脱离地图”产卵,每当地图向他们滚动时,他们就会向玩家设定的X轴移动?我认为这会使事情简单化,但这不是目前真正的问题

我试图为该运动工作的当前代码是:

def move_towards_player(self, player):
        # Find direction vector (dx, dy) between enemy and player.
        dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
        dist = math.hypot (dx, dy)
        dx, dy = dx / dist, dy / dist # Normalize
        # Move along this normalized vector towards the player
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed
但是它不起作用,这是通过导入数学模块实现的。 (我知道我不需要y形运动,只是想先让它工作)

下面是代码的其余部分--

Zombie.py:

import pygame
from pygame.locals import *
import random
import math

class ZombieEnemy(pygame.sprite.Sprite):
    def __init__(self, x=300, y=360):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('images/zombie.png')
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

all_zombies = pygame.sprite.Group()


for i in range( 50 ):
    new_x = random.randrange( 0, 10000)       # random x-position
    # new_y = random.randrange( 0, )      # random y-position
    all_zombies.add(ZombieEnemy(new_x))         # create, and add to group
我不确定我是否应该为敌人的移动创建一个全新的类,或者我的搭档目前在播放器上做什么,并且让精灵动画和移动正常工作

但以下是我目前掌握的主要代码:

import pygame
from Zombie import *
import math
from pygame.locals import *
pygame.init()
​
win = pygame.display.set_mode((900,567))
​
pygame.display.set_caption("Power Rangers ZOMBIES")
​
walkRight = [pygame.image.load('images/walk1.png'), pygame.image.load('images/walk2.png'), pygame.image.load('images/walk3.png'), pygame.image.load('images/walk4.png'), pygame.image.load('images/walk5.png'), pygame.image.load('images/walk6.png')]
walkLeft = [pygame.image.load('images/leftwalk2.png'), pygame.image.load('images/leftwalk3.png'), pygame.image.load('images/leftwalk4.png'), pygame.image.load('images/leftwalk5.png'), pygame.image.load('images/leftwalk6.png'), pygame.image.load('images/leftwalk7.png')]
bg = pygame.image.load('images/background.png')
char = pygame.image.load('images/standingstill.png')
clock = pygame.time.Clock()
​
class Player(pygame.sprite.Sprite):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 0
        self.isJump = False
        self.left = False
        self.right = False
        self.walkCount = 0
        self.jumpCount = 10
​
    def draw(self, win):
        if self.walkCount + 1 >= 18:
            self.walkCount = 0
​
        if self.left:
            win.blit(walkLeft[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.right:
            win.blit(walkRight[self.walkCount//3], (self.x,self.y))
            self.walkCount +=1
        else:
            win.blit(char, (self.x,self.y))
​
class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load('images/background.png')
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location
​
BackGround = Background('images/background.png', [0,0])
​
# def redrawGameWindow():
#     win.blit(bg, (0,0))
#     man.draw(win)

#     pygame.display.update()
​
#mainloop
man = Player(100, 340, 40, 60)
run = True
while run:
    clock.tick(27)
​
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
​
    keys = pygame.key.get_pressed()
​
    if keys[pygame.K_LEFT] and man.x > man.vel:
        BackGround.rect.left = BackGround.rect.left + int(10)
        man.x -= man.vel
        man.left = True
        man.right = False
    elif keys[pygame.K_RIGHT]: #and man.x < 500 - man.width - man.vel:
        BackGround.rect.left = BackGround.rect.left - int(10)
        man.x += man.vel
        man.right = True
        man.left = False
    else:
        man.right = False
        man.left = False
        man.walkCount = 0

    if not(man.isJump):
        if keys[pygame.K_SPACE]:
            man.isJump = True
            man.right = False
            man.left = False
            man.walkCount = 0
    else:
        if man.jumpCount >= -10:
            neg = 1
            if man.jumpCount < 0:
                neg = -1
            man.y -= (man.jumpCount ** 2) * 0.5 * neg
            man.jumpCount -= 1
        else:
            man.isJump = False
            man.jumpCount = 10

    # redrawGameWindow()
    for zombie in all_zombies:
        zombie.move_towards_player(Player)
    all_zombie.update()
    win.blit(BackGround.image, BackGround.rect)
    man.draw(win)
    pygame.display.flip()
    all_zombies.draw(screen)
​
pygame.quit()
导入pygame
从僵尸导入*
输入数学
从pygame.locals导入*
pygame.init()
​
win=pygame.display.set_模式((900567))
​
pygame.display.set_标题(“强力游骑兵僵尸”)
​
walkRight=[pygame.image.load('images/walk1.png')、pygame.image.load('images/walk2.png')、pygame.image.load('images/walk3.png')、pygame.image.load('images/walk4.png')、pygame.image.load('images/walk5.png')、pygame.image.load('images/walk6.png')]
walkLeft=[pygame.image.load('images/leftwalk2.png')、pygame.image.load('images/leftwalk3.png')、pygame.image.load('images/leftwalk4.png')、pygame.image.load('images/leftwalk5.png')、pygame.image.load('images/leftwalk6.png')、pygame.image.load('images/leftwalk7.png')]
bg=pygame.image.load('images/background.png')
char=pygame.image.load('images/standingstill.png')
clock=pygame.time.clock()
​
职业玩家(pygame.sprite.sprite):
定义初始值(自、x、y、宽度、高度):
self.x=x
self.y=y
self.width=宽度
自我高度=高度
self.vel=0
self.isJump=False
self.left=False
self.right=False
self.walkCount=0
self.jumpCount=10
​
def抽签(自我,赢):
如果self.walkCount+1>=18:
self.walkCount=0
​
如果self.left:
blit(walkLeft[self.walkCount//3],(self.x,self.y))
self.walkCount+=1
elif self.right:
blit(walkRight[self.walkCount//3],(self.x,self.y))
self.walkCount+=1
其他:
win.blit(char,(self.x,self.y))
​
类背景(pygame.sprite.sprite):
def_uuuinit_uuu(自我、图像文件、位置):
pygame.sprite.sprite.\uuuu初始化(self)\uuuu调用sprite初始值设定项
self.image=pygame.image.load('images/background.png')
self.rect=self.image.get_rect()
self.rect.left,self.rect.top=位置
​
背景=背景('images/BackGround.png',[0,0])
​
#def重画游戏窗口():
#温·布利特(背景,(0,0))
#男子平局(胜利)
#pygame.display.update()
​
#主回路
男子=运动员(1003404060)
运行=真
运行时:
时钟滴答作响(27)
​
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
运行=错误
​
keys=pygame.key.get_pressed()
​
如果键[pygame.K_左]和man.x>man.vel:
BackGround.rect.left=BackGround.rect.left+int(10)
man.x-=man.vel
左=真
对=错
elif keys[pygame.K_RIGHT]:#和man.x<500-man.width-man.vel:
BackGround.rect.left=BackGround.rect.left-int(10)
man.x+=man.vel
正确的
左=假
其他:
对=错
左=假
man.walkCount=0
如果没有(man.isJump):
如果键[pygame.K_SPACE]:
man.isJump=True
对=错
左=假
man.walkCount=0
其他:
如果man.jumpCount>=-10:
负=1
如果man.jumpCount<0:
负=-1
man.y-=(man.jumpCount**2)*0.5*neg
man.jumpCount-=1
其他:
man.isJump=False
man.jumpCount=10
#重画游戏窗口()
对于所有_僵尸中的僵尸:
僵尸。向玩家移动(玩家)
所有_zombie.update()
win.blit(BackGround.image,BackGround.rect)
男子平局(胜利)
pygame.display.flip()
所有僵尸。绘制(屏幕)
​
pygame.quit()

我无法运行代码,但我发现有两个问题

1-
移动到\u玩家必须在类内
僵尸敌人

# --- classes ---

class ZombieEnemy(pygame.sprite.Sprite):

    def __init__(self, x=300, y=360):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('images/zombie.png')
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

    def move_towards_player(self, player):
        # Find direction vector (dx, dy) between enemy and player.
        dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
        dist = math.hypot (dx, dy)
        dx, dy = dx / dist, dy / dist # Normalize
        # Move along this normalized vector towards the player
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed 

 # --- other ---

 all_zombies = pygame.sprite.Group()
2-您必须在主循环中使用它

    for zombie in all_zombies:
        zombie.move_towards_player(player)
while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # If keystroke is pressed check right, left.
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            #playerX_change = -2.0
            BackGround.rect.left = BackGround.rect.left + 2.5
        if event.key == pygame.K_RIGHT:
            #playerX_change = 2.0
            BackGround.rect.left = BackGround.rect.left - 2.5
    # if event.type == pygame.KEYUP:
    #     if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
    #         BackGround.rect.left = 0

    # --- updates/moves ---

    playerX += playerX_change

    for zombie in all_zombies:
        zombie.move_towards_player(player)
    all_zombies.update()

    # --- draws ---

    screen.blit(BackGround.image, BackGround.rect)
    player(playerX,playerY)
    all_zombies.draw(screen)
    pygame.display.flip()
主回路中

    for zombie in all_zombies:
        zombie.move_towards_player(player)
while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # If keystroke is pressed check right, left.
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            #playerX_change = -2.0
            BackGround.rect.left = BackGround.rect.left + 2.5
        if event.key == pygame.K_RIGHT:
            #playerX_change = 2.0
            BackGround.rect.left = BackGround.rect.left - 2.5
    # if event.type == pygame.KEYUP:
    #     if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
    #         BackGround.rect.left = 0

    # --- updates/moves ---

    playerX += playerX_change

    for zombie in all_zombies:
        zombie.move_towards_player(player)
    all_zombies.update()

    # --- draws ---

    screen.blit(BackGround.image, BackGround.rect)
    player(playerX,playerY)
    all_zombies.draw(screen)
    pygame.display.flip()
但在这里我看到了另一个问题-你的函数期望玩家作为类实例,里面有
self.rect
(类似于
zombiefeedy
),但你把
player
作为分离变量
playerImg
playerX
playerX
playerX\u change


因此,您必须创建类
Player
,或者您必须在
中使用
playerx,playery
,而不是
Player.rect.x
,将\u移向\u Player
player.rect.y

所有僵尸的函数都应该在类内
僵尸敌人
-所以
向玩家移动
应该在类内
僵尸敌人
,但你在类外拥有它。你不能在课外使用
self
。@furas我已经厌倦了,每当我运行游戏时,僵尸仍然会在屏幕上产卵,不会随着背景移动,或者每当玩家输入任何东西时。你从不使用
move_to_player
,所以敌人永远不会移动。@furas那么,我会做一个if语句吗?如果玩家向玩家移动?喜欢把它加入游戏循环吗?对不起,谢谢你的帮助!在所有僵尸中,你必须像这样对僵尸使用
:僵尸。移动到玩家(玩家)
-b