【问题标题】:Pygame surface location seems to be different than what it is on the screen?Pygame 表面位置似乎与屏幕上的位置不同?
【发布时间】:2018-12-23 10:54:39
【问题描述】:

我正在尝试用 pygame 制作一个虚拟手机类的程序,只是为了试验它,但我遇到了一个问题。我已经加载了一张图片,然后将它放到屏幕的左下方。但是当我执行print(imagename.get_rect()) 时,它会在屏幕的 0、0 处打印出一个位置。 鼠标也在那里与它发生碰撞。我不明白什么?

def aloitus(): #goes back to the home screen
    cls() #clears the screen
    tausta = pygame.image.load("./pyhelin.png") #load background
    tausta = pygame.transform.scale(tausta, (360, 640)) #scale it 
    screen.blit(tausta, (0, 0)) #blit it
    alapalkki = pygame.Surface((600, 100)) #ignore
    alapalkki.set_alpha(120)
    alapalkki.fill(blonk)
    screen.blit(alapalkki, (0, 560))
    global messenger #this is the thing!
    messenger = pygame.image.load("./mese.png").convert_alpha() #load image
    print(messenger.get_rect()) #print its location
    messenger = pygame.transform.scale(messenger, (60,65)) #scale it to the correct size
    screen.blit(messenger, (10, 570)) # blit on the screen
    update() #update screen
aloitus() # at the start of the program, go to the home screen
while loop: #main loop
    for event in pygame.event.get():
         if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if messenger.get_rect().collidepoint(x, y): #messenger is the image defined earlier
                #do things
                print("hi")

预期的结果是,当单击图像时会打印“hi”。 实际结果是,当点击左上角时,会打印 hi。

【问题讨论】:

    标签: python pygame pygame-surface


    【解决方案1】:

    get_rect 返回一个带有默认左上角坐标 (0, 0) 的 pygame.Rect。您需要在之后设置坐标或将它们作为关键字参数传递给get_rect

    我建议将矩形分配给另一个变量并通过以下方式之一设置坐标:

    messenger_rect = messenger.get_rect()
    messenger_rect.x = 100
    messenger_rect.y = 200
    # or
    messenger_rect.topleft = (100, 200)
    # or pass the coords as an argument to `get_rect`
    messenger_rect = messenger.get_rect(topleft=(100, 200))
    

    还有更多 rect attributes 可以分配坐标:

    x,y
    top, left, bottom, right
    topleft, bottomleft, topright, bottomright
    midtop, midleft, midbottom, midright
    center, centerx, centery
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多