【发布时间】:2014-03-02 05:27:57
【问题描述】:
我遇到了一个非常烦人的问题,我希望我们当中有人知道这可能会有所帮助。
问题在于,为代表玩家而创建的精灵卡在其生成位置。一个生成位置,顺便说一句,它不是我告诉它生成的地方,并且不会接受在其他地方生成的坐标,它只会在屏幕的左上角生成。我让我的程序在运行时连续打印出它的位置以及更改其坐标的命令,并且它正在接收应有的更新信息,精灵只是不会移动。它的作用就像我让它撞到一堵无法穿透的墙上一样。
相关的python/pygame代码:
class Player(pygame.sprite.Sprite):
#This class represents the Player.
def __init__(self):
#Set up the player on creation.
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
#draws on the sprite
self.image = pygame.image.load("spaceship.png").convert_alpha()
# scales sprite based on resolution
self.image = pygame.transform.scale(self.image,(width // 8,height // 7))
self.rect = self.image.get_rect()
self.rect.y = y #sets initial spawn point to x and y which are variables
self.rect.x = x # set to the middle of the screen earlier in the program
def update(self):
# Update the player's position. #
# Set the player's x,y coordinates to that of movex, movey
self.rect.x = movex #movex and movey are a means for changing x and y via player input
self.rect.y = movey
....调用播放器类.....
player = Player() #creates the player sprite that gets manipulated via the player class
player_list.add(player) #adds the new player to both lists to aid in tracking and updating
all_sprites_list.add(player)
......意思是在游戏功能里面......
all_sprites_list.update() #forces all sprites within the list to refer to their class's update function
all_sprites_list.draw(screen) #auto magically draws all the new sprites
pygame.display.flip() #actually renders the updated imagery for entire program.
这应该是与所讨论的精灵相关的任何内容。如果需要,我当然可以提供更多信息,我只是不想在这里发布大量代码,因为它可能会吓跑人们。 :p
编辑:x 和 y 最初设置为高度//2 和宽度//2 的全局变量,其中高度和宽度用于分辨率
movey 和 movex 全局设置为 0,但在游戏通过游戏函数循环运行时更新。 movey,movex 示例代码:
if event.type == KEYDOWN: #ship movement
if event.key == K_LEFT:
movex=-6
if event.key == K_RIGHT:
movex=+6
if event.key ==K_UP:
movey=-6
if event.key ==K_DOWN:
movey=+6
if event.key == K_a:
movex=-6
if event.key == K_d:
movex=+6
if event.key ==K_w:
movey=-6
if event.key ==K_s:
movey=+6
x += movex
y +=movey
更新!!!!!!
self.rect.x = movex #movex and movey are a means for changing x and y via player input
self.rect.y = movey
这一行只需:
self.rect.x += movex #movex and movey are a means for changing x and y via player input
self.rect.y += movey
在等号之前添加加号会通过添加 movey,movex 来更改 self.rect.(x,y) 值,而不是重复地将它们分配给它们的值。
【问题讨论】:
-
x、y、movex和movey来自哪里?这些肯定是相关的。 -
精灵的左上角在 0,0 处生成,这似乎应该是默认位置。那么问题就变成了,为什么它会忽略我的 self.rect.y/x 语句并在那里产生然后拒绝更新的位置?
标签: python pygame sprite render