I made a 2D platformer game with pygame. I am struggling to figure out how to determine the direction an object is moving in.
For example: say the player is coming from above since his y velocity is greater than zero, then the problems are that his gravitation is acting on him constantly; this means that if he comes from the left side, his y velocity is greater than zero (so this if statement will get triggered even though I want the left-side-if statement to get triggered).
The source code for this is the following: `
if self.hits:
for platform in self.hits:
if self.player.vel.y > 0:
self.player.rect.y = platform.rect.top
self.player.vel.y = 0
if self.player.vel.y < 0:
self.player.rect.top = platform.rect.bottom
self.player.vel.y = 0
if self.player.vel.x > 0:
self.player.rect.right = platform.rect.left
if self.player.vel.y < 0:
self.player.rect.left = platform.rect.right
That is why I created some limitations for the recognition of each four directions: `
if self.hits:
for platform in self.hits:
if self.player.rect.bottom >= (platform.rect.top) and self.player.rect.bottom <= (platform.rect.top + 16)\
and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
self.player.pos_bottom.y = platform.rect.top
self.player.vel.y = 0
elif self.player.rect.top <= (platform.rect.bottom) and self.player.rect.top >= (platform.rect.bottom - 16)\
and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
self.player.rect.top = platform.rect.bottom
self.player.vel.y = 0
elif self.player.rect.right >= (platform.rect.left) and self.player.rect.right <= (platform.rect.right + 10) and self.player.vel.x >= 0\
and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
self.player.rect.right = platform.rect.left
self.player.vel.x = 0
elif self.player.rect.left <= (platform.rect.right) and self.player.rect.left >= (platform.rect.right - 10) and self.player.vel.x <= 0\
and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
self.player.rect.left = platform.rect.right
self.player.vel.x = 0`
This code limitates the zone in which the players direction is getting recognized, but brings a lot of bugs with it and is also really ugly.