【问题标题】:Pygame moving image not appearing on moving backgroundPygame移动图像没有出现在移动背景上
【发布时间】:2020-01-16 15:51:20
【问题描述】:

所以,我的 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()   

【问题讨论】:

  • 请详细说明,谢谢:)
  • 我尝试通过 redrawGameWindow 显示更新。我应该怎么做呢?谢谢:)

标签: python background pygame character


【解决方案1】:

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

【讨论】:

  • 谢谢!!但我应该如何改变它?我应该更改变量名称还是将它们移动到差异位置?是的,图像移动了 :) 谢谢!
  • @User - 好吧,您希望它如何工作?当障碍物移出屏幕时会发生什么?他们以后会回来吗?不一样的来了?一个简单的更改是在obstacleX 变量位于大于窗口宽度的位置时将其重新设置为0(假设它向左->向右移动)。将检查放在代码更新障碍物位置的位置。
  • 我游戏的目标是让画面从左向右移动,然后有一个角色要跳过障碍物。障碍物也随着屏幕从左向右移动。屏幕动画一直很好,但我的角色应该跳过的障碍物不断消失……不知道为什么。有点像你在没有 wifi 时玩的游戏(霸王龙游戏)
  • 哦,我也有这个代码(完全忘记添加它 - 抱歉!!)
  • 如果障碍物X
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 2014-11-25
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多