【问题标题】:How can I make a sprite fall from a random x position in pygame如何使精灵从pygame中的随机x位置掉落
【发布时间】:2020-04-26 16:16:46
【问题描述】:

所以我想做的是让我的播放器在从屏幕顶部掉下来的物体周围导航。到目前为止,我有障碍物的随机 x 位置,但它不会继续从顶部掉下来,只会卡住。这是它的样子: Black "obstacle" stuck in the top.

这是我目前的代码:

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()

width = 640
height = 480
DISPLAYSURF = pygame.display.set_mode((width,height),0,32)
pygame.display.set_caption('Photon')
background = pygame.image.load('background.png')

mspeed = 5
hspeed = 5

hole = pygame.image.load('bHole.png')
sprite = pygame.image.load('photon.png')
spritex = 0
spritey = 0

holex = random.randint(0,260)
holey = 0

while True:
    if holey < 460:
        holey -= hspeed
    DISPLAYSURF.blit(background,(0,0))

    DISPLAYSURF.blit(sprite,(spritex,spritey))

    DISPLAYSURF.blit(hole,(holex,holey))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()


    keys_pressed = pygame.key.get_pressed()

    if keys_pressed[pygame.K_LEFT]:
        spritex -= mspeed

    if keys_pressed[pygame.K_RIGHT]:
        spritex += mspeed

    if keys_pressed[pygame.K_UP]:
        spritey -= mspeed

    if keys_pressed[pygame.K_DOWN]:
        spritey += mspeed


    if spritex > 620:
        spritex = 620
    if spritex < 0:
        spritex = 0
    if spritey > 460:
        spritey = 460
    if spritey < 0:
        spritey = 0

    if holey < 460:
        holey += hspeed
    elif holey > 460:
        holex = random.randint(0,260)
        holey = 0


    pygame.display.update()
    fpsClock.tick(FPS)
    print('PX:', spritex, 'PY:', spritey, 'HX:', holex, 'HY:', holey)

任何帮助都会非常有帮助,因为我现在不知道该怎么做。

【问题讨论】:

    标签: python pygame game-development


    【解决方案1】:

    在屏幕更新循环的每次迭代中,您都有两个 if holey &lt; 460: 检查。第一个减去hspeed,另一个加上加回来——所以它们相互抵消,物体无论在哪里都会“卡住”。

    【讨论】:

    • 不敢相信我错过了!
    • 1h4t3l33t5p34k:是的,有时只需要第二双眼睛……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多