0

I built a simple gravity simulation shown here:

enter image description here

At first, I used a variable timestep, by calculating how much it takes for one update, and applying that to the next one - standard stuff.

However, this method reduces determinism, and results can vary from simulation to simulation - something I definitely do not want.

I figured that I should use a fixed time step (10 seconds), but then I noticed that the simulation would speed up and down in regular intervals (of around 1 second).

Why is that happening? Does it have to do anything with Python itself?


The code

The main loop:

while run:
    uni.update(10)

    for event in pygame.event.get():
        if event.type == QUIT:
            run = False

The update method:

def update (self, dt):
    self.time += dt

    for b1, b2 in combinations(self.bodies.values(), 2):
        fg = self.Fg(b1, b2)

        if b1.position.x > b2.position.x:
            b1.force.x -= fg.x
            b2.force.x += fg.x
        else:
            b1.force.x += fg.x
            b2.force.x -= fg.x


        if b1.position.y > b2.position.y:
            b1.force.y -= fg.y
            b2.force.y += fg.y
        else:
            b1.force.y += fg.y
            b2.force.y -= fg.y


    for b in self.bodies.itervalues():
        ax = b.force.x/b.m
        ay = b.force.y/b.m

        b.position.x += b.velocity.x*dt
        b.position.y += b.velocity.y*dt

        nvx = ax*dt
        nvy = ay*dt

        b.position.x += 0.5*nvx*dt
        b.position.y += 0.5*nvy*dt

        b.velocity.x += nvx
        b.velocity.y += nvy

        b.force.x = 0
        b.force.y = 0
4

0 回答 0