Pygame:.set_clip返回列表中的第一个值,而不是请求的值

时间:2013-02-09 11:12:33

标签: python pygame sprite rect

我正在尝试为精灵表格返回的图像制作动画 我正在使用.set_clip来返回精灵表的一部分。一切看起来都应该起作用 但是.set_clip返回我提供的列表中的第一个Rect值,而不是我要求的列表中的项目。
我的代码

import pygame, sys
from pygame.locals import *

xList = (6, 27,48,69)
yList = (24,24,24,24)
wList = (21,21,21,21)
hList = (32,32,32,32)
ani_pos = list(zip(xList, yList, wList, hList))
sprite_num = 0

class Player:

    def __init__(self): 
        playerSheet = pygame.image.load('MainChar1.png').convert() # load sprite sheet
        playerSheet.set_clip(pygame.Rect(ani_pos[sprite_num]))
        self.player = playerSheet.subsurface(playerSheet.get_clip())
        self.x = 320
        self.y = 240
    def draw(self, DISPLAYSURF):
        DISPLAYSURF.blit(self.player, (self.x, self.y))
        self.player.set_colorkey(255, 0, 255)# set sprite background invisible

class Background:

    def __init__(self):
        dirtTile = pygame.image.load('DirtBackground.png').convert()
        dirtTile.set_clip(pygame.Rect(0, 0, 863, 1103))
        self.background = dirtTile.subsurface(dirtTile.get_clip())
        self.x = -111
        self.y = -311      
    def draw(self, DISPLAYSURF):
        DISPLAYSURF.blit(self.background, (self.x, self.y))

pygame.init()
FPS = 30
FPSCLOCK = pygame.time.Clock()

# set up the window
WINDOWWIDTH = 640 # size of windows' width in pixels
WINDOWHEIGHT = 480 # size of windows' height in pixels
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('farm game')
player = Player()
background = Background()
pygame.key.set_repeat(1,0) # (mSec to begin repeat, mSec between repeats)
running = True

while running: # the main game loop

    DISPLAYSURF.fill (255,255,255)
    background.draw(DISPLAYSURF)
    player.draw(DISPLAYSURF)
    pygame.display.flip()
    FPSCLOCK.tick(FPS)

    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()
            running = False

        elif event.type == KEYDOWN:
            if event.key == K_d:
                background.x -= 4
                sprite_num = 2

1 个答案:

答案 0 :(得分:1)

  

我正在使用.set_clip来返回一部分精灵表。

不,你没有。您使用subsurface返回精灵表的一部分。


我不知道你对set_clip的看法是什么,但它可能不是它实际上做的:

  

这是一个矩形,表示Surface上可以修改的唯一像素。

更好地解释了SDL docs

  

设置曲面的剪切矩形。当此曲面是blit的目标时,只会绘制剪辑矩形内的区域。


  

但.set_clip返回我提供的列表中的第一个Rect值,而不是我要求的列表中的项目。

set_clip根本不返回任何列表的任何Rect值。

当您致电pygame.Rect(ani_pos[sprite_num])时,您创建的Rect列表ani_pos中的值位于索引sprite_num,而sprite_num为{{ 1}}调用0方法时。

您将__init__方法中创建的Surface存储在__init__字段中,但实际上并未对其进行更改。如果要创建某种动画,则应每player帧更改一次。您将n更改为sprite_num,但由于您再也没有使用该值,因此无法执行任何操作。