如何让我的精灵留在屏幕上和绿色平台上? 精灵一直在屏幕上掉下来,有人可以帮忙吗?
player_image = pygame.image.load("bcquestchar.png")
player_image.set_colorkey(WHITE)
def draw_background(screen, x, y):
pygame.draw.line(screen, ground_GREEN, [0, 400], [700, 400], 200)
pygame.draw.line(screen, sky_BLUE, [0,0], [700,0], 400)
pygame.draw.line(screen, sky_WHITE, [0, 270], [700, 270], 150)
#jumping player definition
class Player(pygame.sprite.Sprite):
def __init__(self):
self.playing = False
self.color = BLUE
self.x = 50
self.y = 210
self.goalY= 450
self.gameover = False
def jump(self):
self.goalY -= 45
def draw(self, screen):
screen.blit(player_image, [self.x, self.y])
#create player
player = Player()
答案 0 :(得分:0)
只需制作另一个功能,确保当精灵的底部触及屏幕底部时,它会停在那里,等待任何其他命令。例如:
if self.x >= 1000:
self.x = 1000
上述代码表示如果x
位置大于或等于1000,则将x
设置为1000,这样它就不会更低。数量也可以根据您的需求进行调整。您还需要调用update
函数,因为我们需要它才能工作:
def update(self): #Put the function into your Player class
if self.x >= 1000:
self.x = 1000
#Put the following the while loop or just call it
player = Player()
player.update() #Call update()
答案 1 :(得分:0)
移动玩家后,您必须检查其位置并进行更正。
您应该使用pygame.Rect
,因为它有帮助。
它不是完整代码,它不会使用rect
方法来检查冲突,但它会显示如何启动它。
# jumping player definition
class Player(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load("bcquestchar.png")
self.image.set_colorkey(WHITE)
self.playing = False
self.color = BLUE
# use rect to keep size and position
self.rect = self.image.get_rect()
self.rect.x = 50
self.rect.y = 210
self.goalY= 450
self.gameover = False
#self.speed_x = 0
#self.speed_y = 0
#self.gravity = 1
def jump(self):
self.goalY -= 45
def draw(self, screen):
screen.blit(self.image, self.rect)
#def event_handler(self, event):
# # if pressed key then change speed
def update(self):
# move player
#self.rect.x += self.speed_x
#self.rect.y += self.speed_y
#self.speed_y += self.gravity
# check collision with grass
if self.rect.bottom > grass_rect.top:
# player below grass then move it up
self.rect.bottom = grass_rect.top:
# ---
# draw other objects
def draw_background(screen, x, y):
pygame.draw.line(screen, ground_GREEN, grass_rect, 200)
# ---
# create player
player = Player()
# create object rect to draw it and check collision with player
grass_rect = pygame.Rect(0, 400, 700, 400)
# move player and check collision with objects
player.update()
您有玩家rect
和草rect
- 您可以将玩家底部与草top
进行比较。
在" Platformer Example"的源代码中查看更多内容。