简体   繁体   English

如何让敌人跟随pygame中的玩家?

[英]How to make an enemy follow a player in pygame?

I am making a top-down shooter and want my zombie to follow my character, and my program uses a main loop. 我正在制作一个自上而下的射手,并希望我的僵尸跟随我的角色,我的程序使用一个主循环。 The position of my character is x and y and he is controlled by the arrow keys. 我的角色的位置是x和y,他由箭头键控制。 I have a zombie that as of right now randomly spawns at the left edge of the screen when shot at. 我有一个僵尸,当时拍摄的时候,它会在屏幕的左边缘随机产生。 How can I make the zombie follow my position from where it spawns? 如何让僵尸跟随我产生的位置?

This is the zombie function: 这是僵尸功能:

def makezombie():
    global zom
    zom = Rect (0,randint(0, height-40), 49, 38)
    return zom

I set zombie=makezombie() 我设置zombie = makezombie()

In my main loop I have the following: 在我的主循环中,我有以下内容:

for shot in shots:
    if zombie.collidepoint(shot[X],shot[Y]):
        zombie=makezombie()
        points+=1000
        impact.play()
        blood.play()

I'm not sure I fully understand the question but essentially what you can do is take the players (x, y) coordiantes and the zombies (x, y) coordinate. 我不确定我是否完全理解这个问题,但基本上你可以做的是采用球员(x,y)坐标和僵尸(x,y)坐标。 Assuming (xp, yp) are the players coordinates and (xz, yz) are the zombies, you can use the following algorithm to find the direction from the zombie to the player: 假设(xp,yp)是玩家坐标而且(xz,yz)是僵尸,你可以使用以下算法来找到从僵尸到玩家的方向:

import math
(dx, dy) = ((xp - xz)/math.sqrt((xp - xz) ** 2 + (yp - yz) ** 2), 
            (yp - yz)/math.sqrt((xp - xz) ** 2 + (yp - yz) ** 2))

Then in the main loop you want to update the zombies x and y position coordinates by doing newCoord = (xp + dx * spped, yp + dy * speed) where speed is some number of pixels that you want the zombie to move per loop. 然后在主循环中,你想通过执行newCoord =(xp + dx * spped,yp + dy * speed)更新僵尸x和y位置坐标,其中速度是你希望僵尸每个循环移动的一些像素数。 Then redraw the zombie at this new position. 然后在这个新位置重绘僵尸。

Hope that helps! 希望有所帮助! If not, please clarify the question. 如果没有,请澄清问题。

If you know about vector math ( ie: euclid ), you can use vector subtraction. 如果您了解矢量数学(即: euclid ),则可以使用向量减法。

zombie_speed = 50 # pixels / an update
player = Vector2(player.rect.x, player.rect.y)
zombie = Vector2(zombie.rect.x, zombie.rect.y)
movement = player - zombie
movement.normalize()
movement *= zombie_speed

Then add movement's x,y values to zombie's Rect() 然后将运动的x,y值添加到zombie的Rect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM