使用 Haskell 的 Gloss 库,我正在尝试模拟星空。视觉方面(以不同的速度和大小在屏幕上绘制“星星”)正在发挥作用。然而,由于某种原因,恒星并没有随机分布,导致模拟具有模式。我在爆炸模拟中也遇到了这个问题,但为了简单起见,我暂时不考虑这个问题。到目前为止,这是我的代码的简化版本:
type Position = (Float, Float)
type Velocity = (Float, Float)
type Size = Float
type Speed = Float
type Drag = Float
type Life = Int
type Particle = (Position, Velocity, Speed, Drag, Life, Size)
-- timeHandler is called every frame by the gloss ‘Play’ function. It's being passed
-- the delta time and the world it needs to update.
timeHandler dt world = world {rndGen = mkStdGen (timer world),
timer = (timer world) + 1,
stars = spawnParticle world (rndGen world) : updateParticles (stars world) dt world}
randomFloat :: StdGen -> Float -> Float -> Float
randomFloat rand min max = fst $ randomR (min, max) rand
spawnParticle :: World -> StdGen -> Particle
spawnParticle world gen = ((pos, (1 * speed, 0), speed, 1, 0, size), snd (split gen))
where pos = (px', py')
px' = randomFloat gen (-600) (-500)
py' = randomFloat gen (-250) 250
speed = size * (randomFloat gen 100 300) -- the smaller a particle, the slower
size = randomFloat gen 0.1 1.3
updateParticles :: [Particle] -> Float -> World -> [Particle]
updateParticles [] _ _ = []
updateParticles (x:xs) dt world | fst(posPart x) > 500 = updateParticles xs dt world
| otherwise = updatedPart : updateParticles xs dt world
where pos' = updateParticlePosition dt x world
updatedPart = (pos', velPart x, speedPart x, 1, 0, sizePart x)
注意:velPart
等speedPart
是从给定粒子中获取属性的函数。同样,绘图工作正常,所以我将省略该代码。updateParticlePosition
简单地将速度添加到恒星的当前位置。
我认为这个问题与我的随机生成器没有正确传递这一事实有关,但我太困惑了,无法提出解决方案......非常感谢任何帮助!