Pygame - 更流畅的运动 [英] Pygame - Smoother Movement

查看:65
本文介绍了Pygame - 更流畅的运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 main_screen 上添加了一个对象/图像,该对象名为 cancer_cell.我在这里尝试做的是我希望对象平滑移动.我必须反复按下箭头键才能让它保持移动.我如何让它移动 while 箭头键被按下?

I have added an Object/Image on the main_screen, the object is called cancer_cell. What I'm trying to do here is that I want the object move smoothly. I have to repeatedle press on the arrow keys to keep it moving. How do I make it move while arrow keys are pressed ?

代码如下:

exitgame = False
cellpos_x = 0
cellpos_y = cancer_cell.get_rect().height*2
while not exitgame:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitgame = True
            quitgame()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                cellpos_x -= 10
            if event.key == pygame.K_RIGHT:
                cellpos_x += 10


    gameplay_bg = pygame.image.load("/Users/wolf/Desktop/python/img/gameplay_bg.png").convert()
    main_screen.fill(white)
    main_screen.blit(gameplay_bg, [0,0])
    main_screen.blit(cancer_cell, [cellpos_x, cellpos_y])
    pygame.display.flip()
    clock.tick(20)

有人告诉我在如何使用pygame.KEYDOWN尝试解决方案:但这也不起作用.或者我做错了:

someone told me to try the solution at How to use pygame.KEYDOWN: but that didn't work either. Or maybe i did it wrong:

if event.type == pygame.KEYDOWN:
    key_pressed = pygame.key.get_pressed()
    if key_pressed[pygame.K_LEFT]:
        cellpos_x -= 10
    if key_pressed[pygame.K_RIGHT]:
        cellpos_x += 10

推荐答案

问题已解决

我通过从 FOR 循环中取消缩进这部分就解决了这个问题虽然没有退出游戏:

I have solved the problem by just unindenting this part from the FOR loop while not exitgame:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitgame = True
            quitgame()

    key_pressed = pygame.key.get_pressed()
    if key_pressed[pygame.K_LEFT]:
        cellpos_x -= 10
    if key_pressed[pygame.K_RIGHT]:
        cellpos_x += 10

这篇关于Pygame - 更流畅的运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆