I'm trying to create a game in which there are rocks on the screen that move when the player moves, as the player is centered in the screen, and instead of the player moving, the terrain does. The problem that I have is that whenever a key is pressed down, about only half of the rocks shift up 2 more pixels, and when released, they go back to the original state. Here is the code for the player update function that controls the movement of terrain, where obx and oby are the coordinates added onto the terrain when moving:
if forward == True:
grassx += 2
obx += 2
self.forward_walk += 1
if 15 >= self.forward_walk >= 0:
self.image = pygame.image.load("person_left_walk_1.png")
if 30 >= self.forward_walk >= 15:
self.image = pygame.image.load("person_left_walk_2.png")
if self.forward_walk >= 30:
self.forward_walk = 0
if back == True:
grassx -= 2
obx -= 2
self.backward_walk += 1
if 15 >= self.backward_walk >= 0:
self.image = pygame.image.load("person_right_walk_1.png")
if 30 >= self.backward_walk >= 15:
self.image = pygame.image.load("person_right_walk_2.png")
if self.backward_walk >= 30:
self.backward_walk = 0
if up == True:
grassy += 2
oby += 2
self.up_walk += 1
if 15 >= self.up_walk >= 0:
self.image = pygame.image.load("person_back_walk_1.png")
if 30 >= self.up_walk >= 15:
self.image = pygame.image.load("person_back_walk_2.png")
if self.up_walk >= 30:
self.up_walk = 0
if down == True:
grassy -= 2
oby -= 2
self.down_walk += 1
if 15 >= self.down_walk >= 0:
self.image = pygame.image.load("person_down_walk_1.png")
if 30 >= self.down_walk >= 15:
self.image = pygame.image.load("person_down_walk_2.png")
if self.down_walk >= 30:
self.down_walk = 0
This is the rock class, it uses the obx and oby from the previous function (they are global variables):
class Obstacle(pygame.sprite.Sprite):
original_x = 0
original_y = 0
def __init__(self,image,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.original_x = self.rect.x
self.original_y = self.rect.y
self.mask = pygame.mask.from_surface(self.image)
def update(self):
self.rect.x = self.original_x + obx
self.rect.y = self.original_y + oby
Ask me if you need any further information. Thanks!
obyandobxcome from in theObstacle.updatefunction? It appears to me that they are never initialized, unless they are globals.def update(obx,oby)then calling update each time you want to change the coordinates. For instance:if up == True: oby+=1 Obstacle_instance.update(0,oby).