如何使敌人跟随玩家? Pygame

时间:2020-01-20 17:55:30

标签: python python-3.x pygame

我知道之前已经有人问过这个问题,但是我无法使其与我的代码一起使用。

我认为这是敌人应该跟随玩家的地方。我不确定该如何实施。

我希望敌人跟随玩家,当他们遇到玩家时,游戏结束。我也希望它能够与多个敌人一起使用。

# player class
class player:
    def __init__(self, x, y, w, h, xChange, yChange, vel):
        self.x = x # plater x value
        self.y = y # player y value
        self.w = w # player w (width)
        self.h = h # player h (height)
        self.xChange = xChange # player xChange (to add to x value to move player horizontally)
        self.yChange = yChange # player yChange (to aad to y value to move player vertically)
        self.vel = vel # velocity of player (needed for collision)

# enemy class
class enemy:
    def __init__(self, x, y, w, h):
        self.x = x # enemy x value
        self.y = y # enemy y value 
        self.w = w # enemy w (width) value
        self.h = h # enemy h (height) value

# ----------------------------------------------------------------

"""enemy's x value (random value) (we pick 750 because the enemy width is 50 and
the screen width is 800. If we set the random value to 800, then the enemy has a
chance of spawning outside of the screen.)"""
enemyX = random.randint(0, 700)

"""enemy's y value (random value) (we pick 540 because the enemy height is 60
and the screen height is 600. If we set the random value to 600, the enemy has a
chance of spawning outside of the screen.)"""
enemyY = random.randint(0, 540) # enemy's y value

score = 0 # score set to 0. Will update in while loop.

rec = player(50, 50, 24, 32, 0, 0, 5) # the player's values (x, y, w, h, xChange, yChange, vel)
redRec = enemy(enemyX, enemyY, 24, 32) # the enemy's values (x, y, w, h)

# mainloop #
def mainloop():
    global running, score, intro, sprite, next_zombie_time

    while running:
        """keeps filling window with the background image"""
        window.blit(background, (0, 0))
        pygame.time.delay(25) # delay
        for event in pygame.event.get(): # for every event in game
            if event.type == pygame.QUIT: # if I exit the game
                quitGame()

            if event.type == pygame.KEYUP: # if any keys are let go
                if event.key == pygame.K_a: # if key a
                        rec.xChange = 0 # set xChange to 0 (stop moving rec)

                if event.key == pygame.K_d: # if key d
                    rec.xChange = 0 # set xChange to 0 (stop moving rec)

                if event.key == pygame.K_w: # if key w
                    rec.yChange = 0 # set xChange to 0 (stop moving rec)

                if event.key == pygame.K_s: # if key s
                    rec.yChange = 0 # set xChange to 0 (stop moving rec)

            if event.type == pygame.KEYDOWN: # if any keys are pressed
                if event.key == pygame.K_F4: # if key F4
                    pygame.quit() # set running to false

                if event.key == pygame.K_a: # if key a
                    rec.xChange += -5 # add -5 to xChange (move rec left)
                    sprite = spriteLeft

                if event.key == pygame.K_d: # if key a
                    rec.xChange += 5 # adds 5 to xChange (move rec right)
                    sprite = spriteRight

                if event.key == pygame.K_w: # if key a
                    #adds -5 to yChange (moves rec up). Yes, this is supposed to say up.
                    rec.yChange += -5
                    sprite = spriteUp

                if event.key == pygame.K_s: # if key a
                    # adds 5 to yChange (moves rec down). Yes, this is supposed to say down.
                    rec.yChange += 5
                    sprite = spriteDown

                # pause key to pause game 
                if event.key == pygame.K_o: # if key o
                    running = False # set running to false
                    intro = False # intro set to False
                    pauseMenu() # pauseMenu is called




        rec.x += rec.xChange # add rec's xChange to x (to do the moving)
        rec.y += rec.yChange # adds rec's yChange to y (to do the moving)


        # ----------------BOUNDARIES------------------------------
        if rec.x <= 0: # if rec's x is less than or equal to 0 (if tries to escape screen)
            rec.x  = 0 # rec's x is set to 0 so it won't go off screen.

        """(we pick 750 because the player width is 50 and the screen width is 800.
        If we set it to 800, then the player can go outside of screen."""   
        if rec.x  >= 750: # if rec's x is greater than or equal to 750 (if tries to escape screen)
            rec.x  = 750  # set rec's x to 750 so it won't go off screen

        if rec.y <= 0: # if rec's y is less than or equal to 0 (if tries to escape screen)
            rec.y = 0 # set rec's y to 0 so it won't go off screen
        """we pick 540 because the player height is 60 and the screen height is 600.
            If we set it to 600, then the player can go outside of screen"""
        if rec.y >= 540: # if rec'y is greater than or equal to 540 (if tries to escape screen) 
            rec.y = 540 # set rec's y to 540 so it won't go off screen  

        #enemy.update(delta_time, player)
        collisions = detCollision(rec.x, rec.y, rec.w, rec.h, redRec.x, redRec.y, redRec.w, redRec.h)
        # activate the redrawWin function
        redrawWin(collisions)



1 个答案:

答案 0 :(得分:1)

您需要一些信息来做到这一点。首先,您需要玩家与敌人之间的距离。您可以使用File "/home/user/Scrivania/PyInteraph-1.0/test/pyinteraph/pyinteraph", line 162, in <module> from libinteract import libinteract as li File "/home/user/Scrivania/PyInteraph-1.0/test/lib/python/libinteract/libinteract.py", line 8, in <module> from innerloops import LoopDistances ImportError: /home/user/Scrivania/PyInteraph-1.0/test/lib/python/libinteract/innerloops.so: undefined symbol: sqmI 这样的while( !q.isEmpty() ) { System.out.println(q.remove()); } 函数来计算距离。然后,您想使用math.hypot函数来计算弧度之间的夹角。请注意,此函数首先接受distance = (math.hypot(enemy.x - player.x, enemy.y - player.y) )个位置参数。您可以按以下方式使用

math.atan2

现在要让敌人朝玩家的方向移动,就可以做到

y

查看其工作原理http://setosa.io/ev/sine-and-cosine/。 您甚至可以通过这样设置玩家之间的距离条件,来增加玩家想要跟随敌人的距离范围。

angle_radians = (math.atan2(enemy.y - player.y , enemy.x - player.x))

您还可以通过将正弦和余弦乘以相同的数字来控制速度,这是有效的,因为它们是比率。看起来像这样

     enemy.y += math.sin(angle_radians) 
     enemy.x += math.cos(angle_radians)

对于您问题的最后一部分,如果您希望它适用于所有敌人,我建议您将游戏对象添加到列表中。例如,您可以将敌人添加到列表中 让他们跟随玩家。可以这样说

if distance < range:

最终结果可能看起来像这样:

 enemy.y += math.sin(angle_radians) * speed # Note both speeds must be the same nnumber
 enemy.x += math.cos(angle_radians) * speed

编辑 这是一个很好的youtube视频的链接,描述了所有这些 https://www.youtube.com/watch?v=DVYDkHdsTIM