Lee
Lee

Reputation: 31

Removing the first items from a dynamic array when it gets to a certain size

I am making a gravity simulation which shows the trajectory of planets. Each planet leaves behind a trail of dots when it moves, which is stored in a dynamic array. However, when the trail becomes longer the paint event has to draw more every time so the frame rate decreases. I want to delete the first dots when the array gets larger than say 1000 dots.

This is in the code for the paint event:

For drawTrail As Integer = 0 To planet.trailX.Count - 1
    e.Graphics.DrawEllipse(trailcolour, planet.trailX(drawTrail), planet.trailY(drawTrail), 1, 1) 'Draw a pixel at the planet's current location
Next

And this is in a timer event which ticks 60 times a second:

trailDots += 1
ReDim Preserve planet.trailX(trailDots)
ReDim Preserve planet.trailY(trailDots)
planet.trailX(trailDots) = planet.displayX
planet.trailY(trailDots) = planet.displayY

I tried adding this code in the timer tick:

If trailDots > 1000 Then
    trailDots -= 1
    ReDim Preserve planet.trailX(trailDots - 1)
    ReDim Preserve planet.trailY(trailDots - 1)
End If

But once the trail got to 1000 dots the simulation crashes with the message "IndexOutOfRangeException was unhandled" on the line "planet.trailX(trailDots) = planet.displayX"

How do I fix this?

Upvotes: 1

Views: 31

Answers (1)

Kake_Fisk
Kake_Fisk

Reputation: 1165

First of all, I think you are removing the newest element and not the oldest.

Anyway, the reason it crashes is because you first decrease trailDots by one and then redim it to trailDots - 1, effectively shrinking it by 2 elements. You can make the following changes to fix that.

If trailDots > 1000 Then
    trailDots -= 1
    ReDim Preserve planet.trailX(trailDots)
    ReDim Preserve planet.trailY(trailDots)
End If

I would also recommend to initialize trailDots to 0 and make the following changes.

planet.trailX(trailDots - 1) = planet.displayX
planet.trailY(trailDots - 1) = planet.displayY

But as Andew said, you should rather use circular buffer for this problem.

Upvotes: 1

Related Questions