如何实现相机并对平台游戏进行碰撞检测?

时间:2014-04-03 00:26:30

标签: python pygame sprite

我需要帮助使屏幕在整个关卡中跟随播放器并同时处理碰撞。我已经单独完成了两个并且它们工作正常但我在同时做两个都遇到了麻烦。

这是我尝试过的。如果您需要更多代码,我很乐意将其包含在内。

我做错了什么?我现在已经尝试了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

1 个答案:

答案 0 :(得分:0)

请查看以下问题,因为他们可能会回答您的问题。

Example1

Example 2

只是fyi示例2是一个更好的例子,因为我相信它可以回答你的问题。它会随着你的角色不断地回答侧面滚动以及相机的以下内容,但是示例1本身就有一些非常有趣的东西。