Search code examples
pythonpython-3.xcollision-detectionpyglet

How to calculate if a shape is under another in pyglet


I'm making an endless runner using pyglet. The game
I'm trying to determine the height of the floor under the player. Every floor is a class:

class Floor():
    def __init__(self, width, height, offset, batch=None):
        self.width = width
        self.height = height

        self.floor = shapes.Rectangle(offset, 0, self.width, self.height, color=(9, 197, 0), batch=batch)
    def move(self, amount):
        self.floor.x -= amount

So i added a method to the class to calculate if the floor is under the player (the player is also a shape):

    def under_player(self, player):
        if player.x <= self.floor.x and self.floor.x + self.width >= player.x:
            return True
        return False

To calculate now the floor height the player is under, i made this function (floors is a list of Floor classes):

def calc_under_floor():
    global floors, player
    for floor in floors:
        if floor.under_player(player):
            return floor.height
    return -100

The problem is that the condition in under_player for checking the if the player is under this floor is wrong. I can't find a working solution. Is there a way i can fix this?


Solution

  • I hope I found the solution. At least it works :)

        def under_player(self, player):
            if player.x + 50 >= self.floor.x and player.x <= self.floor.x + self.floor.width:
                return True
            return False