Trying to make a “solid” block in pygame

♀尐吖头ヾ 提交于 2020-01-05 14:03:32

问题


So i want my player to not be able to pass through the block, but it teleports to the other side, any idea why? here's my code:

def update(self, collidable):
    self.rect.x += self.hspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)
    for collided_object in collision_list:
        if (self.hspeed > 0):
            # right direction
            self.rect.right = collided_object.rect.left

        elif (self.hspeed < 0):
            # left direction
            self.rect.left = collided_object.rect.right

    self.rect.y += self.vspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)   
    for collided_object in collision_list:
        if (self.vspeed > 0):
         # down direction
            self.rect.bottom = collided_object.rect.up

        elif (self.vspeed < 0):
            # up direction
            self.rect.top = collided_object.rect.bottom

Thanks alot in advance!


回答1:


Sorry about the last answer. Here's one that should fix your code. The new code is:

def update(self, collidable):
    self.rect.x += self.hspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)
    for collided_object in collision_list:
        if (self.hspeed > 0):
            # right direction
            self.rect.left = collided_object.rect.right # rect.right and rect.left swapped

        elif (self.hspeed < 0):
            # left direction
            self.rect.right = collided_object.rect.left # rect.right and rect.left swapped

    self.rect.y += self.vspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)   
    for collided_object in collision_list:
        if (self.vspeed > 0):
         # down direction
            self.rect.bottom = collided_object.rect.up

        elif (self.vspeed < 0):
            # up direction
            self.rect.top = collided_object.rect.bottom

The lines I changed were in the self.hspeed collision. When you hit one side, instead of sticking to that side, you were locking to the other side of the cube. In short I swapped rect.left and rect.right, but you could have swapped the > 0 and < 0 but I wanted to keep that in the right odder so it looked nicer...



来源:https://stackoverflow.com/questions/32189978/trying-to-make-a-solid-block-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!