Reputation: 9
I am doing a remake of doodle jump. The problem i have encountered is that the direction at which the object is facing gets iterated over. What I mean by this, is something like this: If the direction is equal to 'right', but, you decided to change the direction further through the loop, so the direction should become 'left', but since the loop starts from the first line, it just almost immediately changes back to direction 'right'.
like so: loop: right if something happens: left
The problem is that the loop starts from line one, so it immediately makes it back to right
Here is the code:
class Player():
def __init__(self, x, y):
self.direction = -1
player_img = pygame.image.load('player1.png')
if self.direction == 1:
self.player = pygame.transform.scale(player_img, (100, 100))
if self.direction == -1:
player = pygame.transform.scale(player_img, (100, 100))
self.player = pygame.transform.flip(player, True, False)
self.rect = self.player.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
def update(self):
dx = 0
dy = 0
# Key windings
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
dx -= 5
self.direction = -1
if key[pygame.K_RIGHT]:
dx += 5
self.direction = 1
Upvotes: 0
Views: 251
Reputation: 6166
So this is how I would redefine Your class:
class Player():
def __init__(self, x, y):
self.direction = -1
self.player_img_left = pygame.transform.scale(pygame.image.load('player1.png'), (100, 100))
self.player_img_right = pygame.image.flip(self.player_img_left, True, False)
self.rect = self.player_img_left.get_rect()
self.direction = 1
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
def update(self):
dx = 0
dy = 0
# Key windings
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
dx -= 5
self.direction = 1
if key[pygame.K_RIGHT]:
dx += 5
self.direction = -1
if self.direction == -1:
img = self.player_img_right
elif self.direction == 1:
img = self.player_img_left
and at the end You would want to blit img
(also I may have messed up the left and right)
Upvotes: 0