python - 如何在pygame python中找到精灵中心
问题描述
我在 win32 上使用 Python 3.6.5,我想找到我的 sprite 的中心,以便将它准确地定位在 x 轴上。我有什么办法可以做到这一点?
额外信息:pip 版本 18.0、计算机 Dell Inspiron 15、3000 系列。pygame.image.load()
我使用该函数加载了精灵。
解决方案
pygame.image.load()
仅加载图像。您可能必须使用
pygame.transform.scale()
如果您的图像分辨率已经定义,您将不需要它,您可以使用两个变量来指示您的图像宽度和高度。
在 python 中,X 和 Y 位置从左上角开始。所以你的窗口的左上角是(0,0),右下角是(window_width,window_height)。代码中的所有元素都是一样的。
此代码打印精灵(或任何图像)的中心:
import pygame
pygame.init()
display_width = 800 #define size of window
display_height = 600
img_pos_x = 100 #define position of image
img_pos_y= 100
img_size_x = 40 #define size of image
img_size_y = 40
img = pygame.image.load("image.png") #load image
img = pygame.transform.scale(img,(img_size_x,img_size_y)) #resize image
screen = pygame.display.set_mode((display_width, display_height)) #display window
gameExit = False
screen.blit(img, (img_pos_x,img_pos_y)) #display image
img_center = (img_pos_x + img_size_x/2, img_pos_y + img_size_y/2) #find image center
while not gameExit:
for event in pygame.event.get(): #define what to do when game not quit
if event.type == pygame.QUIT:
gameExit = True
pygame.quit()
quit()
print(img_center) #print coordinates of image center
这段代码可以根据不同的用途进行修改,这只是为了展示它是如何工作的。希望你能明白我的意思。
编辑:澄清和更正
这一行:
img_center = (img_pos_x + img_size_x/2, img_pos_y + img_size_y/2)
找到图像的左上角坐标 (x, y),右上角是 x + 图像宽度,所以中间是图像宽度的一半,我们通过将一半图像宽度添加到左上角坐标来找到中间坐标。Y 坐标也一样, (X,Y) 都指向任何图像的中间。
推荐阅读
- ios - 获取屏幕大小的结果以显示在 Objective-C 的文本字段中
- python - python selenium href地址太长无法获取正确数据
- javascript - 使用两个不同的 Firestore 字段执行操作
- javascript - 如何使这个打字稿映射功能变得不那么复杂?
- git - 为什么我的 github url 权限在我推送时被拒绝?
- r - fviz_cluster,更改 pt 的颜色以反映键
- regex - 正则表达式查找(/替换)字符串中的多个字符实例
- python - 带有串行端口的 Python 线程等待其他线程完成
- java - 使用 java 下载 Blob 给了我一个巨大的文件
- sql - 在这种情况下,如何从存储过程中返回正确的开始日期值?