首页 > 解决方案 > 我是 pygame 的新手,希望得到 get_rect() 的帮助吗?

问题描述

我是 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], (x, y))
        stepIndex += 1
    elif move_right:
        screen.blit(right[stepIndex//4], (x,y))
        stepIndex += 1
    else:
        screen.blit(stationary, (x,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()

标签: pythonpygame

解决方案


pygame.Surface.get_rect.get_rect()返回一个具有Surface对象大小的矩形,该矩形始终从 (0, 0) 开始。请注意,Surface对象没有位置。Surface放置在具有该功能的显示器上的某个位置blit
矩形的位置可以由关键字参数指定。例如,可以使用关键字参数指定矩形的中心centerpygame.Rect这些关键字参数在返回之前应用于 的属性(请参阅pygame.Rect关键字参数的完整列表):

soil_rect = soilImg.get_rect(topleft = (soilX, soilY))
stationary_rect = stationary.get_rect(topleft = (x, y))

您可以删除变量x,和y,并使用and代替。soilXsoilYsoil_rectstationary_rect


推荐阅读