我需要帮助使屏幕在整个关卡中跟随播放器并同时处理碰撞。我已经单独完成了两个并且它们工作正常但我在同时做两个都遇到了麻烦。
这是我尝试过的。如果您需要更多代码,我很乐意将其包含在内。
我做错了什么?我现在已经尝试了3天了。
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