问题描述
我是 pygame 的新手并试图理解 get_rect() 但仍然出现错误请帮助 就像试图让我的“静止”人不要进入那个“土壤”
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((680,340))
pygame.display.set_caption("Collector")
icon = pygame.image.load('knight.png')
pygame.display.set_icon(icon)
background = pygame.image.load('background.png')
我想先从这张静止的图片开始,然后移动到那个运动
stationary = pygame.image.load(os.path.join('standing.png'))
# Another (faster) way to do it - using the sprites that face right.
right = [None]*10
for picIndex in range(1,10):
right[picIndex-1] = pygame.image.load(os.path.join('pictures/R' + str(picIndex) + ".png"))
picIndex+=1
left = [None]*10
for picIndex in range(1,10):
left[picIndex-1] = pygame.image.load(os.path.join('pictures/L' + str(picIndex) + ".png"))
picIndex+=1
soilImg = pygame.image.load('soil.png')
soilX = 150
soilY = 200
x = 200
y = 223
vel_x = 5
vel_y = 5
jump = False
move_left = False
move_right = False
stepIndex = 0
def soil(x,y):
screen.blit(soilImg,(x,y))
# Draw the Game
def draw_game():
global stepIndex
screen.blit(background,(0,0))
if stepIndex >= 36:
stepIndex = 0
if move_left:
screen.blit(left[stepIndex//4],y))
stepIndex += 1
elif move_right:
screen.blit(right[stepIndex//4],y))
stepIndex += 1
else:
screen.blit(stationary,y))
这里可能有问题
# Feels like something is wrong here
soil_rect = soilImg.get_rect()
stationary_rect = stationary.get_rect()
这里可能有问题
stationary_rect.x = soil_rect.x
stationary_rect.y = soil_rect.y
# Main Loop
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_game()
# Movement
userInput = pygame.key.get_pressed()
if userInput[pygame.K_LEFT]:
x -= vel_x
move_left = True
move_right = False
elif userInput[pygame.K_RIGHT]:
x += vel_x
move_left = False
move_right = True
else:
move_left = False
move_right = False
stepIndex = 0
if jump == False and userInput[pygame.K_SPACE]:
jump = True
if jump == True:
y -= vel_y*2
vel_y -= 1
if vel_y < -10:
jump = False
vel_y = 10
if userInput[pygame.K_ESCAPE]:
run = False
if x < -15:
x = -15
elif x > 635:
x = 635
if y > 223:
y = 223
soil(soilX,soilY)
pygame.time.delay(30)
pygame.display.update()
解决方法
pygame.Surface.get_rect.get_rect()
返回一个具有 Surface 对象大小的矩形,该矩形总是从 (0,0) 开始。
请注意,Surface 对象没有位置。 Surface 使用 blit
函数放置在显示屏上的某个位置。
矩形的位置可以通过关键字参数指定。例如,矩形的中心可以用关键字参数 center
指定。这些关键字参数在返回之前应用于 pygame.Rect
的属性(有关关键字参数的完整列表,请参阅 pygame.Rect
):
soil_rect = soilImg.get_rect(topleft = (soilX,soilY))
stationary_rect = stationary.get_rect(topleft = (x,y))
您可以删除变量 x
、y
、soilX
和 soilY
,并改用 soil_rect
和 stationary_rect
。