开发者

Python/Pygame Making An Object Follow Another Object

I Have Been Trying for days on how to do this. Basically You Control开发者_开发知识库 A Player, And zombies follow you.

Problem Is, I Cant Seem To Get The Zombies To Follow! I Tried If Statements For Example

    if playerx > zombiex:
        zombiex=zombiex - 2
        screen.blit(zombie,(zombiex,zombiey))

aaaaaand That Didnt Work.... :/

Any Ideas?


Maybe this is what you searched for.

def length(x, y):
    return (x ** 2 + y ** 2) ** .5

def norm(x, y):
    _len    = length(x, y)
    return x / _len, y / _len

class ZombieController(object):

    def __init__(self, zombie_view_range):
        self._zombs = []
        self.append = self._zombs.append
        self._range = zombie_view_range

    def NextFrame(self, player_pos):
        px, py      = player_pos
        _range      = self._range
        for zombie in self._zombs:
            x, y    = zombie.position
            dx, dy  = px - x, py - y
            _len    = length(dx, dy)
            if _len <= _range:
                speed       = zombie.speed
                direction   = norm(dx, dy)
                zombie.positon  = x + direction[0] * speed, y + direction[1] * speed


First, can't answer your whole questions as there's not enough information. How doesn't it work exactly?

Second, if you want the zombies to follow, you need thier coordinates to converge with the players so you need something like:

if playerx > zombiex:
    zombiex = zombiex + max(zombiespeed, playerx - zombiex)
elif playerx < zombiex:
    zombiex = zombiex - max(zombiespeed, zombiex - playerx)

NB:

  • I replace 2 with zombiespeed which you define elsewhere so you can change the speed in one place for future.
  • I use max() to ensure the zombie won't move PAST the player when very close.
  • You'd obviously do the same for the y direction too.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜