所以我正在制作一个PyGame,棒球从上面掉下来,底部的用户必须接球。球以随机的速度下降,但是我很难让球以不同的速度下落。
例如,我目前的球代码是:
def update(self):
if self.is_falling:
"""Move the ball down."""
self.y += random.randint(10, 200) / 100
self.rect.y = self.y
在这里,当我运行程序时,球以不同的速度下降,但它几乎不同。如果我改变数字使其达到(10,20000)/ 100那么每个球都会快速下降。那是什么原因?似乎随机数不是那么随机。我使用的功能错了吗?
我想让每个球以非常不同的速度下降,例如一个非常快,另一个非常慢。我希望它是随机数,以便用户可以玩许多不同的速度......
我想知道,如果有随机函数,我可以设置生成的随机数之间的特定间隔?或者我应该尝试不同的方法?如果是这样,我该怎么做?
我是Python的初学者,所以如果你能尽可能简单地解释,那将非常感激!
部分问题是亚像素距离。我认为你的主要问题是你的y
运动。看看self.y +=
的等式,一半的时间会导致像素距离只有一个像素。当这被添加到self.rect时,舍入(或截断)将使小于1像素的量消失。例如,生成的随机整数是99,然后除以100,是0.99的像素。在python中int(0.99)
为零。因此,大约一半时间,运动为零,另一半,自int(150/100)
=> 1
以来,运动仅为1个像素。 (每190个瞬间一个像素将是2个像素。)
def update(self):
if self.is_falling:
"""Move the ball down."""
self.y += random.randint(10, 200) / 100
self.rect.y = self.y
同样在@ 6502指出,这将产生一个生涩的随机运动。在类__init__
中生成像素更新速度会更好,并坚持下去。
def __init__( self, ... ):
...
self.fall_speed = random.randint(10, 200) # pixels per update
def update(self):
if self.is_falling:
"""Move the ball down."""
self.y += self.fall_speed
self.rect.y = self.y
我喜欢根据实时计算进行移动。这需要物体速度和帧间定时来计算物体移动了多少。我喜欢这个,因为如果你想将重力(或其他)添加到程序中,很容易计算出新的位置。
class FallingSprite( pygame.sprite.Sprite ):
""" A falling sprite. Falls at a constant velocity in real-time """
def __init__( self, image ):
pygame.sprite.Sprite.__init__( self )
self.image = image
self.rect = self.image.get_rect()
self.fall_speed = random.randint(10, 200) # pixels / second
self.last_update = int( time.time() * 1000.0 )
self.rect.center = ( random.randrange( 0, WINDOW_WIDTH ), 0 )
def update( self ):
# There may have been movement since the last update
# so calculate the new position (if any)
if ( self.fall_speed > 0 ):
time_now = int( time.time() * 1000.0 )
time_change = time_now - self.last_update # How long since last update?
if ( time_change > 0 ):
distance_moved = time_change * self.fall_speed / 1000
now_x, now_y = self.rect.center # Where am I, right now
updated_y = now_y + distance_moved
# Did we fall off the bottom of the screen?
if ( updated_y > WINDOW_HEIGHT ):
# sprite disappears
self.kill()
else:
self.rect.center = ( now_x, updated_y )
self.last_update = time_now
如果这是Python 2则存在问题
random.randint(10, 200) / 100
因为除法将在整数数学中完成。你应该用
random.randint(10, 200) / 100.
另一个问题是你在每次更新时选择随机步骤(可能是每一帧),这不会产生速度的错觉,而是更多的随机抖动。选择一个像你正在做的随机速度可能会更好,但至少在几帧或甚至整个秋季动画中保持相同。
只需稍微调整一下数字,20000就是从200开始的大幅跳跃。因为你现在获得的数值是10/100和200/100。这是.1到2像素,所以我不认为它们会有很大的不同。你跳到10/100到20000/100,这是一个巨大的速度,大约200像素的帽子与原来的2.所以这是你的问题。也许是200到2000甚至200到2500的范围。你不需要这么大的调整,因为你说球开始很快下降。我以前做过同样的游戏,我可以说你只需稍微调整一下这些数字。