Search code examples
pythonpygamespriteplatform

How to make a moving platform using Pygame


I am trying to implement a moving platform into my code,like one that moves side to side and the limites on how far from side to side could be set, however i am struggling to seem to find a way to do it with the way i am making my map and levels work, i am pasting my full code for my main game code below, however I am also going to link the code for the full platform game [here][1] incase anyone wants to check it out. Thanks for the help.


Solution

  • I am only starting out on my journey in gamedev with pygame, but I think what you want to do is add a update method to your moving platform, which decreases or increases (depending on what direction you want it to move in) the x value of it's rectangle, until the left or right of it reaches a certain point or the platform collides with another. Then you would invert it's direction. Here is some code that might work:

    class PlatMoving(Entity):
        def __init__(self, pos, *groups):
            super().__init__(Color("#10eb93"), pos, *groups)
            self.dx = 1
    
        def update(self):
            self.x += 10 * self.dx
    

    And in the update method here would be some pseudo code to check for collisions:

    if pygame.sprite.spritecollide(self, *the platform group you want it to collide with*, False):
        self.dx *= -1
    

    I believe something like this should work! Good luck!