I am trying to create my own primitive 2D graphics engine. The main component of the game is shooting from various shells at enemies. I need this component to work before I can continue.
That I am now moving my projectile along a line passing through the Starting point (x, y) and Target point (x1, x2). I use the linear function y = mx + b
. The problem is that, as I update the position of the projectile, it causes an inconsistent speed depending on the slope of the line. (large slopes make him leave faster).
Here is the basic structure of the game loop in which I run:
private void executeGameLoop() { long nextFrameStart = System.nanoTime(); while(panel.getRunning()) { do { panel.update(); nextFrameStart += FRAME_PERIOD; } while(nextFrameStart < System.nanoTime()); long remaining = nextFrameStart - System.nanoTime(); panel.repaint(); if (remaining > 0) { try { Thread.sleep(remaining / 1000000); } catch(Throwable e) { System.out.println(e.getMessage()); } } } }
This is just a structure and graphics update mechanism. Each time you call panel.update
shell updates its position, taking into account certain circumstances. Here are the methods that update the projectile:
This says that the projectile has a target and sets line information.
public void setHasTarget(boolean hasTargetIn) { if(hasTargetIn) { deltaX = getTargetX() - getX(); deltaY = getTargetY() - getY(); slope = deltaY / deltaX; intercept = getY(); System.out.println("y = " + slope + "x + " + intercept);
This next method sets the position to the next step in the line. (X is updated by speed, y is updated by x)
public void setNext() { float temp = (slope) * (getX() + velocity) + intercept; System.out.println("Slope: " + (slope) * (getX() + velocity)); System.out.println("Current: (" + getX() + ", " + getY() + ")"); System.out.println("Next: (" + (getX() + velocity) + ", " + (getY() + temp) + ")"); setX(getX() + velocity); setY(temp); }
This last method calls setNext()
and is called by the main loop.
public void update() { if(hasTarget) setNext(); }
As I said, given my current code, the result when I launch is a projectile that moves around the screen at inconsistent speeds, depending on the slope of the line. I would like to be able to change my code so that the projectile moves on the screen at a constant speed along any path. Thank you in advance for any help.