【问题标题】:How to find the position of a Rect in python?如何在python中找到一个Rect的位置?
【发布时间】:2022-12-05 02:34:25
【问题描述】:

我试图制作一个移动矩形对象的代码(通过 get_rect 函数获得),但我需要它的坐标以使其移动 1 个像素(如果有任何其他方法可以做到这一点,请告诉我。)

这是代码:

  1. 导入系统、pygame
  2. pygame.init()
  3. 尺寸=宽度,高度=1920,1080
  4. 黑色 = 0, 0, 0
  5. 屏幕 = pygame.display.set_mode(大小)
  6. ball = pygame.image.load("ball.png")
  7. rectball = ball.get_rect()
  8. 当为真时:
  9. 对于 pygame.event.get() 中的事件:
  10. if event.type == pygame.QUIT: sys.exit()
  11. rectball.move()
  12. 屏幕填充(黑色)
  13. screen.blit(球,矩形球)
  14. pygame.display.flip()

    您会注意到第 11 行的参数未填充。这是因为我打算让它坐标 + 1。

【问题讨论】:

    标签: python


    【解决方案1】:

    如果我是正确的,我认为是 rect.left 或 rect.top 给出了它。另一种方法是创建另一个矩形并检查矩形是否在其中。

    【讨论】:

      【解决方案2】:
      To move a rect object in Pygame, you can use the move_ip() method. This method takes two arguments, the x and y coordinates to move the rect by. For example, if you want to move the rect one pixel to the right and one pixel down, you can use the following code:
      
      rectball.move_ip(1, 1)
      
      You can also use the x and y attributes of the rect to move it by a certain amount. For example, if you want to move the rect one pixel to the right, you can use the following code:
      
      rectball.x += 1
      
      Note that this will only move the rect object and not the image that it represents. To move the image on the screen, you will also need to update the position of the ball surface using the blit() method.
      
      Here is an updated version of your code that moves the rect and the image on the screen:
      
      import sys
      import pygame
      
      pygame.init()
      
      size = width, height = 1920, 1080
      black = 0, 0, 0
      
      screen = pygame.display.set_mode(size)
      
      ball = pygame.image.load("ball.png")
      rectball = ball.get_rect()
      
      while True:
          for event in pygame.event.get():
              if event.type == pygame.QUIT:
                  sys.exit()
      
          # Move the rect one pixel to the right and one pixel down
          rectball.move_ip(1, 1)
      
          # Update the position of the ball on the screen
          screen.blit(ball, rectball)
      
          pygame.display.flip()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        • 2011-05-21
        • 2023-03-16
        • 1970-01-01
        • 2014-01-31
        • 2017-10-26
        相关资源
        最近更新 更多