r/processing • u/ONOXMusic • Oct 20 '23
Beginner help request Check so that object doesn't iterate on itself in n-body gravity simulation?
Hey!
Thinking about doing a simple 2D gravity simulator to learn more about objects in processing. Let's say that we have an ArrayList with planets of the class Planet. What I've seen been done is to iterate for every object in the array and check the distance to all the other planets, to calculate the new velocity.
How would I check so that the planet doesn't calculate check itself?
Something like if (currentPlanet != planet[i])
5
Upvotes
7
u/akb74 Oct 20 '23
Yeah, exactly like that. Your implementation of Newton’s gravity equation should check for division by zero anyway and resolve that as no force, just in case any two of your planets happen to find themselves centred on the exact same spot. That means you don’t have to worry about a planet exherting force on itself anyway.
3
u/Simplyfire Oct 20 '23 edited Oct 20 '23
if your for loop is inside a planet class then you can use this.equals(otherPlanet) -
thisrefers to the instance you're inside,equals()checks whether the two are the exact same object in memory andcontinueskips the rest of this loop's code once (but it "continues" iterating on other objects in the array)