Python 使用可移动角色/图像在Pygame中添加边界

Python 使用可移动角色/图像在Pygame中添加边界,python,pygame,boundary,Python,Pygame,Boundary,我一直在创造一个游戏,其中的图像移动根据球员的输入键和键的方法。我想添加边界,这样用户就不能将图像/角色移出显示器(我不想在边界被击中的情况下玩游戏,只是图像/角色不能移动超过边界) 我尝试过好几次,包括切换到按键法,但都失败了。请帮忙,谢谢 基本上你想限制玩家的移动 因此,每次你想“移动”玩家(我猜这是“x_change”/“y_change”),你都需要检查他们在移动后是否仍在你的边界内 示例:屏幕左侧的显示x边界为0像素,右侧为500像素。我只允许实际的运动,如果运动的结果在我的范围内

我一直在创造一个游戏,其中的图像移动根据球员的输入键和键的方法。我想添加边界,这样用户就不能将图像/角色移出显示器(我不想在边界被击中的情况下玩游戏,只是图像/角色不能移动超过边界)


我尝试过好几次,包括切换到按键法,但都失败了。请帮忙,谢谢

基本上你想限制玩家的移动

因此,每次你想“移动”玩家(我猜这是“x_change”/“y_change”),你都需要检查他们在移动后是否仍在你的边界内

示例:屏幕左侧的显示x边界为0像素,右侧为500像素。我只允许实际的运动,如果运动的结果在我的范围内

 boundary_x_lower = 0
 boundary_x_upper = 500

 if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if boundary_x_lower < (x_change - 4): 
                    # I allow the movement if I'm still above the lower boundary after the move.
                    x_change -= 4
            elif event.key == pygame.K_RIGHT:
                if boundary_x_upper > (x_change +4): 
                     # I allow the movement if I'm still below the upper boundary after the move.
                     x_change += 4
boundary_x_lower=0
边界×上=500
如果event.type==pygame.KEYDOWN:
如果event.key==pygame.K_左:
如果边界_x_较低<(x_变化-4):
#如果移动后我仍在下边界上方,我允许移动。
x_变化-=4
elif event.key==pygame.K_RIGHT:
如果边界x_上>(x_变化+4):
#如果我在移动后仍然低于上边界,我允许移动。
x_变化+=4
PS:我被你的代码弄糊涂了,当你向右移动时,你会减法。。。我习惯于2D游戏,如果你向右移动,你会增加玩家的位置。。。如果你走到左边,就减去


请随意调整代码以适合您的项目。基本原理也适用于y轴移动:边界为上下。如果你还有其他问题,尽管问吧

只需将
x
y
值夹在0和显示宽度和高度之间即可

# In the main while loop after the movement.
if x < 0:
    x = 0
elif x + image_width > display_width:
    x = display_width - image_width

if y < 0:
    y = 0
elif y + image_height > display_height:
    y = display_height - image_height
以及将用作blit位置的角色的rect:

rect = characterimg_left.get_rect(center=(x, y))
然后按以下方式移动并夹紧rect:

rect.move_ip((x_change, y_change))
rect.clamp_ip(display_rect)

display.fill(white)
# Blit the image at the `rect.topleft` coordinates.
display.blit(characterimg, rect)
rect = characterimg_left.get_rect(center=(x, y))
rect.move_ip((x_change, y_change))
rect.clamp_ip(display_rect)

display.fill(white)
# Blit the image at the `rect.topleft` coordinates.
display.blit(characterimg, rect)