我遇到了一个问题,我似乎无法上下移动屏幕上的角色。
当我运行代码并按下向下键时,我收到此错误:
AttributeError: 'pygame.Rect' object has no attribute 'down'
当我运行代码并按向上键时,我收到此错误:
AttributeError: 'pygame.Rect' object has no attribute 'up'
代码:
import pygame
class Character():
def __init__(self, ai_settings, screen):
self.screen = screen
self.ai_settings = ai_settings
self.image = pygame.image.load("character.jpg")
self.rect = self.image.get_rect()
self.screen_rect = screen.ge_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.centery = self.screen_rect.centery
self.center = float(self.rect.centerx)
self.center1 = float(self.rect.centery)
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.char_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.char_speed_factor
if self.moving_up and self.rect.up < self.screen_rect.up:
self.center1 += self.ai_settings.char_speed_factor
if self.moving_down and self.rect.down > 0:
self.center1 -= self.ai_settings.char_speed_factor
self.rect.centerx = self.center
self.rect.centery = self.center1
def blitme(self):
self.screen.blit(self.image, self.rect)
这只是字符类python文件而不是主文件。有一个游戏函数文件,它检查键盘输入,然后将self.moving变量设置为True。然后在主文件中调用gamefunctions文件中的定义。我很困惑为什么会发生这种情况,因为我可以让角色左右移动。
答案 0 :(得分:2)
您的问题在于代码的这四行,您可以检查移动和相应的边界碰撞:
class Character():
# Other methods...
def update(self):
# Other if clauses...
if self.moving_up and self.rect.up < self.screen_rect.up:
self.center1 += self.ai_settings.char_speed_factor
if self.moving_down and self.rect.down > 0:
self.center1 -= self.ai_settings.char_speed_factor
# ...
请注意,您正在比较up
对象的down
和Rect
属性,这些属性实际上并不存在。也许你的意思是top
和bottom
?
此外,您的代码逻辑不正确。你正在检查self.rect.bottom
向下移动时是否大于零 - 但是,为了正确实现边界碰撞机制,你应该检查它是否小于屏幕的高度(我认为是self.screen_rect.bottom
当它向下移动时。与self.rect.top
相反 - 你应该检查它是否大于零。
更正了if
声明:
# Replaced .up with .top and .down with .bottom
# Corrected .top and .bottom comparison
if self.moving_up and self.rect.top > 0:
self.center1 -= self.ai_settings.char_speed_factor
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.center1 += self.ai_settings.char_speed_factor