Search code examples
pythonpygletgame-ai

Game ai Line of Sight Python


How would I check to see whether the player is within range of a mob? (I am making a top down game in pyglet) I am making it so that the mobs follow and attack the player if he is within a certain distance of them but I am unsure how to efficiently do this. Would I need to do an "if" statement to see if x > mob.x - 50 and x < mob.x + 50 etc?

I have a class for the mobs

class zombie(pyglet.sprite.Sprite):

    def __init__(self, image, x, y, batch,trees):
            pyglet.sprite.Sprite.__init__(self, image, x, y, batch=None)

I then used several functions as the different actions they could be doing

    def move(self):
        ...
    def idle(self):
        ...

The player's position is "player.x" and "player.y" (the same for the mobs but with "zombie instead of player)

As Joran said, I think finding the distance betweens the mob and the player's coordinates is the best approach and I will make another function to check the distance.

Sorry if this was unclear


Solution

  • you would probably need to calculate the distance between the monster and the player

    sqrt((mob.x-player.x)**2 + (mob.y-player.y)**2)
    

    you could probably simplify it and get rid of the sqrt ...