I need help making the screen follow the player throughout the level as well as handle collisions at the same time. I've done both separately and they work fine but I run into trouble doing both at the same time.
Here is what I've tried. If you need more of the code, I'd be happy to include it.
What am I doing wrong? I've literally been trying to do this for 3 days now.
class Sprite(pygame.sprite.Sprite):
def __init__(self,img):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(img).convert_alpha()
self.rect = self.image.get_rect()
class Player(Sprite):
velocity_y = 0
onGround = True
def update(self):
self.rect.y += self.velocity_y
self.movePlayer()
self.checkBarriers()
self.checkCollision(0, self.velocity_y,terrain_list)
self.checkCollision(Terrain.velocity_x*-1,0,terrain_list)
def movePlayer(self):
if moving_up: # pressing the up arrow key
if self.onGround == True:
self.velocity_y = -SPEED
self.rect.y -= 1
self.onGround = False
if not moving_up: self.velocity_y = SPEED
def checkBarriers(self):
if self.rect.y >= LOWER_BOUNDARY-GROUND_HEIGHT-ROBOT_HEIGHT:
self.onGround = True
self.velocity_y = 0
self.rect.y = LOWER_BOUNDARY-GROUND_HEIGHT-ROBOT_HEIGHT
if self.rect.x <= LEFT_BOUNDARY:
Terrain.velocity_x = 0
def checkCollision(self,xvel,yvel,blocks):
for block in blocks:
if pygame.sprite.collide_rect(block,player):
if xvel < 0: # handle collisions for moving right. (Everything I've tried didnt work)
if xvel > 0: # handle collisions for moving left
if yvel > 0:
self.rect.y = block.rect.y-ROBOT_HEIGHT # player moving down
self.onGround = True
class Terrain(Sprite):
velocity_x = 0
terrain_x = 0
terrain_y = 0
terrain_vel_x = 0
terrain_vel_y = 0
def update(self):
self.rect.x += self.velocity_x
self.movePlayer()
def movePlayer(self):
if moving_right: self.velocity_x = -SPEED
elif not moving_right: self.velocity_x = 0
if moving_left: self.velocity_x = SPEED