I am trying to make a 2D space object simulation using Canvas from Android. While I have finished the physics part, I’m struggling with correctly setting a planet’s spawn location – I want it to spawn relative to the central body (star) which spawns in the centre of the Canvas, as in usual mathematical coordinate system (right = positive X, up = positive Y), however it always ends up spawning relative to the Canvas’ coordinate system zero (down = positive Y), alas the upper left corner of the screen. This is what I have tried:
@Override
public void run() {
Canvas canvas = new Canvas(); // I tried declaring Canvas here
int updates = 0;
int starRadius = 25;
int starMass = 6000;
float planet1posX = canvas.getWidth()/2 + (float) 200.0; // this was expected to work
float planet1posY = canvas.getHeight()/2 - (float) 200.0; // this was expected to work
double planet1velX = 0.5;
double planet1velY = 1.5;
while (running) {
canvas = surfaceHolder.lockCanvas(); // If this is put outside of `while (running)`, it crashes the simulation
int starX = canvas.getWidth()/2;
int starY = canvas.getHeight()/2;
double starDistance1 = Math.sqrt(Math.pow(planet1posX - starX,2) + Math.pow(planet1posY - starY,2));
double accel1X = starMass * (starX - planet1posX) / Math.pow(starDistance1,3);
double accel1Y = starMass * (starY - planet1posY) / Math.pow(starDistance1,3);
planet1velX+=accel1X;
planet1velY+=accel1Y;
planet1posX+=planet1velX;
planet1posY+=planet1velY;
float prevPos1X = planet1posX;
float prevPos1Y = (float) planet1velY;
However, it always spawns relative to Canvas’ zero, completely ignoring the canvas.getWidth()/2
and canvas.Height()/2
. So the question here is how can I get the Canvas’ height and width outside of while (running)
and are there any better solutions to this problem. TIA
Source: Android Questions