且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PyGame-Character 离开屏幕

更新时间:2023-12-01 16:09:16

if not character.get_rect() in screen.get_rect():
    print("error")

我明白你在尝试什么.如果你想检查一个 Rect 是否在另一个里面,使用 contains():

I see what you are trying here. If you want to check if a Rect is inside another one, use contains():

包含()
测试一个矩形是否在另一个矩形内
contains(Rect) ->布尔
当参数完全在 Rect 内时返回 true.

contains()
test if one rectangle is inside another
contains(Rect) -> bool
Returns true when the argument is completely inside the Rect.

如果您只想停止屏幕边缘的移动,一个简单的解决方案是使用 clamp_ip():

If you simply want to stop the movement on the edges on the screen, an easy solution is to use clamp_ip():

clamp_ip()
将矩形内部移动到另一个位置
clamp_ip(Rect) ->无
与 Rect.clamp() 相同 [返回一个新矩形,该矩形被移动到完全位于参数 Rect 内.如果矩形太大而无法放入其中,则它在参数 Rect 内居中,但其大小不会改变.] 方法,而是就地操作.

clamp_ip()
moves the rectangle inside another, in place
clamp_ip(Rect) -> None
Same as the Rect.clamp() [Returns a new rectangle that is moved to be completely inside the argument Rect. If the rectangle is too large to fit inside, it is centered inside the argument Rect, but its size is not changed.] method, but operates in place.

这是一个简单的示例,您无法将黑色矩形移出屏幕:

Here's a simple example where you can't move the black rect outside the screen:

import pygame
pygame.init()
screen=pygame.display.set_mode((400, 400))
screen_rect=screen.get_rect()
player=pygame.Rect(180, 180, 20, 20)
run=True
while run:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: run = False
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]: player.move_ip(0, -1)
    if keys[pygame.K_a]: player.move_ip(-1, 0)
    if keys[pygame.K_s]: player.move_ip(0, 1)
    if keys[pygame.K_d]: player.move_ip(1, 0)
    player.clamp_ip(screen_rect) # ensure player is inside screen
    screen.fill((255,255,255))
    pygame.draw.rect(screen, (0,0,0), player)
    pygame.display.flip()