Calculating Gravity in Java with 2 Bodies

  • Context: Java 
  • Thread starter Thread starter Echilon
  • Start date Start date
  • Tags Tags
    Gravity Java
Click For Summary

Discussion Overview

The discussion revolves around calculating gravitational interactions between multiple bodies in a Java game. Participants explore the implementation details of the gravity calculation, focusing on the accuracy of angles and the coordinate system used in Java for rendering graphics.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant describes their method for calculating gravity between bodies, including the use of a cache to simulate simultaneous gravitational effects.
  • Another participant questions the meaning of "the angles are off" and challenges the approach of subtracting the minimum from the maximum when calculating the gravity angle, suggesting it may introduce errors in determining the correct quadrant.
  • A different participant comments on the unpredictable nature of gravitational movement, noting that it appears random and does not follow expected patterns.
  • One participant suggests that the method of keeping angles positive may be flawed and proposes using the modulo operation instead to constrain the angle within a specific range.
  • Another participant points out that Java's coordinate system has the x-axis directed to the right and the y-axis directed downwards, recommending a potential reversal of the y-axis for proper Cartesian plotting.
  • The original poster mentions that the angles seem randomly offset and shares links to their updated code and an executable jar for further examination.

Areas of Agreement / Disagreement

Participants express differing views on the calculation of angles and the effects of the coordinate system, indicating that there is no consensus on the best approach to resolve the issues raised.

Contextual Notes

Participants have not reached a resolution regarding the accuracy of the gravitational calculations or the handling of angles within the Java coordinate system. There are also unresolved questions about the impact of the coordinate system on the expected behavior of gravity in the game.

Echilon
Messages
3
Reaction score
0
I'm pulling my hair out with this problem. I have two bodies and I'm trying to calculate gravity between them. This is for a game, and there are actually three bodies currently, each frame, I check the distance each one moves due to gravity and store it in a cache (to simulate gravity acting on all objects simultaneously), then apply each vector to the body. This is the code I have:
Code:
public void calculateGravity(GravitationalBody planet) {
	if(isFixed || gravityIndex.contains(planet.hashCode()) || planet.getGravityIndex().contains(this.hashCode())) {
	    return;
	}
	double radiusGravity = this.getCenter().distance(planet.getCenter());
	double force = (Constants.G * this.mass * planet.mass)/(radiusGravity*radiusGravity); // F=GMm/r^2
	double frameRateMs = (Constants.FrameRate/1000.0);
	double gravityAngle = Math.atan2(Math.max(location.y,planet.location.y) - Math.min(location.y,planet.location.y),
	                                 Math.max(location.x,planet.location.x) - Math.min(location.x,planet.location.x)) + (Math.PI/2);
	double gravityDistance = ((force*frameRateMs)/this.mass)*Constants.SpriteGravityMultiplier;
	if(gravityAngle < 0){ // keep angle positive
	    gravityAngle += MaxAngle;
	}
	//        System.out.println("--"+name+"<->"+planet.getName()+"-"+gravityDistance+"px @ "+Math.round(gravityAngle)+"rad");
	if(planet.IsFixed()) { // gravity acts only on this body, pulling it towards the planet
	    gravityCache.add(new Vector2D(gravityAngle, gravityDistance));
	    gravityIndex.add(planet.hashCode());
	} else { // gravity acts on both, pulling them toward each other
	    double resultantGravAngle = (gravityAngle/2),
	           resultantGravDistance = (gravityDistance /2);
	    gravityCache.add(new Vector2D(resultantGravAngle, resultantGravDistance));
	    gravityIndex.add(planet.hashCode());
	    planet.getGravityCache().add(new Vector2D(resultantGravAngle, resultantGravDistance));
	    planet.getGravityIndex().add(planet.hashCode());
	}
}
Assuming Constants.Framerate = 30, Constants.G = 6.667, Constants.SpriteGravityMultiplier = 1e1
The angles are off though, and I'm convinced it has something to do with the coordinate system Java uses for drawing but I can't get it to work properly. Is there anything obvious I've been overlooking?
 
Technology news on Phys.org
1. What do you mean by "the angles are off"?
2. Why do you do this thing with subtracting the min from the max, when you calculate gravityAngle? Maybe I just don't understand but it seems like that ought to introduce error to which quadrant your angle winds up in.
 
Gravity doesn't behave in the way you'd expect, it causes things to move round in seemingly random directions which don't appear to follow a pattern.

The subtracting thing was my way of trying to keep the angle positive. Ie: between 0 and 2pi and avoiding -1pi or 7pi, but I've since found it's easier to just do:
Code:
gravityAngle = gravityAngle % MaxAngle;
 
The angles are off
Could you describe what is "off". Upside down, or random, or a constant difference?

Java plots with the x-axis to the right, and y-axis towards the bottom.
You may need to reverse the y-axis if you want to plot it like on a cartesian plane.
 
They seem to be randomly offset, or at least I can't see a pattern. I've followed suggestions and made some changes to the gravity methods, which I've posted at http://pastebin.com/m5e53fe34 for the syntax highlighting. Maybe if you watch what's happening it would become apparent, so I've uploaded the current game at http://mi6.nu/ml.zip. It's just an executable jar.

Thanks again for any insight. :)
 
Last edited by a moderator:

Similar threads

Replies
7
Views
8K
  • · Replies 28 ·
Replies
28
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 17 ·
Replies
17
Views
4K