试图做一个“固体"在 pygame 中阻止 [英] Trying to make a "solid" block in pygame

查看:52
本文介绍了试图做一个“固体"在 pygame 中阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我希望我的玩家不能穿过方块,但它会传送到另一边,知道为什么吗?这是我的代码:

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

非常感谢!

推荐答案

抱歉上次的回答.这是应该修复您的代码的一个.新代码是:

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

我更改的行是在 self.hspeed 碰撞中.当你撞到一侧时,你不是坚持那一侧,而是锁定在立方体的另一侧.简而言之,我交换了 rect.left 和 rect.right,但您可以交换 > 0 和 <0 但我想把它放在正确的奇怪的地方,这样看起来更好......

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...

这篇关于试图做一个“固体"在 pygame 中阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆