Pygame运动图像不出现在运动背景上

2024-09-30 04:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我的pygame有一个移动的背景,运行良好。现在我想添加一个障碍物(像一块石头),它将位于屏幕底部,并随着背景移动。然而,图像(障碍物)在出现几秒钟后就消失了。我想让石头一次又一次地出现,但是它没有出现。我想不出有什么问题。请帮忙,谢谢

background = pygame.image.load('background.png')
backgroundX = 0
backgroundX2 = background.get_width()
obstacle = pygame.image.load('obstacle.png')
obstacleX = 0
obstacleX2 = obstacle.get_width()


# use procedure for game window rather than using it within loop
def redrawGameWindow():
    # background images for right to left moving screen
    screen.blit(background, (backgroundX, 0))
    screen.blit(background, (backgroundX2, 0))
    man.draw(screen)
    screen.blit(obstacle, (obstacleX, 380))
    screen.blit(obstacle, (obstacleX2, 380))
    pygame.display.flip()
    pygame.display.update()

主回路:

while run:
    screen.fill(white)
    clock.tick(30)
    pygame.display.update()
    redrawGameWindow()  # call procedure

    obstacleX -= 1.4
    obstacleX2 -= 1.4

    if obstacleX < obstacle.get_width() * -10:
        obstacleX = obstacle.get_width

    if obstacleX2 < obstacle.get_width() * -10:
        obstacleX2 = obstacle.get_width()   

Tags: imagegetdisplayloadwidthscreenpygamebackground
1条回答
网友
1楼 · 发布于 2024-09-30 04:31:37

surface.blit()(即:screen.blit)函数获取图像和绘制位置的左上角坐标

在提供的代码中obstacle的两个副本绘制在obstacleXobstacleX2处,其中一个设置为0,另一个设置为图像的宽度。因此,这将导致在窗口左侧第380行,两个图像相邻绘制

如果这些图像在一段时间后不再被绘制,这可能是由以下原因造成的——

  • 变量obstacleXobstacleX2更改为屏幕外位置
  • 正在将图像obstacle更改为空白(或不可见)版本

上面的小代码示例中没有证据,但由于问题表明图像移动,我猜测绘图位置的obstacleXobstacleX2坐标正在更改为屏幕外

编辑:

很明显,您的对象从位置0(窗口左)开始,位置正在更新obstacleX -= 1.4,这将障碍物进一步向左移动。这就是为什么它们开始出现在屏幕上,但很快就消失了

将屏幕尺寸设置为常量,例如:

WINDOW_WIDTH  = 400
WINDOW_HEIGHT = 400

使用这些,而不是在代码中添加数字。如果您决定更改窗口大小,这将减少所需的更改数量,并且还允许基于窗口宽度进行计算

因此,从屏幕上开始设置障碍物

obstacleX  = WINDOW_WIDTH          # off-screen
obstacleX2 = WINDOW_WIDTH + 100    # Further away from first obstacle

在主更新循环中,当项目的位置发生变化时,检查是否需要将其重新循环到播放器前面:

# Move the obstacles 1-pixel to the left
obstacleX  -= 1.4
obstacleX2 -= 1.4   # probably just 1 would be better  

# has the obstacle gone off-screen (to the left)
if ( obstacleX < 0 - obstacle.get_width() ):   
    # move it back to the right (off-screen)
    obstacleX = WINDOW_WIDTH + random.randint( 10, 100 )  

# TODO - handle obstacleX2 similarly

相关问题 更多 >

    热门问题