See the code below. If I move up or left it seems to be faster than moving down or right… but dx == dy !!! Why this is happining?
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.io.InputStream;
import javax.swing.JFrame;
public class Loop1 extends JFrame {
private boolean[] controls = new boolean[5];
int x=100;
int y=100;
double dx=0.1;
double dy=0.1;
public Loop1() {
setSize(300,300);
setResizable(false);
show();
enableEvents(56);
createBufferStrategy(2);
BufferStrategy strategy = getBufferStrategy();
int FPS=60;
int MILI_FRAME_LENGTH = 1000/FPS;
long startTime = System.currentTimeMillis();
int frameCount = 0;
long lastLoopTime = System.currentTimeMillis();
long lastFpsTime=0;
long fps=0;
while (true) {
long delta = System.currentTimeMillis() - lastLoopTime;
lastLoopTime = System.currentTimeMillis();
lastFpsTime += delta;
fps++;
if (lastFpsTime >= 1000) {
this.setTitle(" (FPS: " + fps + ")");
lastFpsTime = 0;
fps = 0;
}
logic(delta);
draw((Graphics2D) strategy.getDrawGraphics());
strategy.show();
frameCount++;
while((System.currentTimeMillis()-startTime)/MILI_FRAME_LENGTH <frameCount) {
Thread.yield();
}
}
}
private void logic(double delta) {
if(controls[0]) {
x-=dx*delta;
} else if(controls[1]) {
x+=dx*delta;
} else if(controls[2]) {
y-=dy*delta;
} else if(controls[3]) {
y+=dy*delta;
}
if(x>300) {
x=0;
}
if(x<0) {
x=300;
}
if(y<0) {
y=300;
}
if(y>300) {
y=0;
}
}
private void draw(Graphics2D g) {
g.setColor(Color.white);
g.fillRect(0,0,300,300);
g.setColor(Color.red);
g.fillOval(x,y,5,5);
}
protected void processKeyEvent(KeyEvent e) {
int[] keys = new int[] {KeyEvent.VK_LEFT,KeyEvent.VK_RIGHT,KeyEvent.VK_UP,KeyEvent.VK_DOWN,KeyEvent.VK_SPACE};
for (int i=0;i<keys.length;i++) {
if (e.getKeyCode() == keys[i]) {
controls[i] = e.getID() == KeyEvent.KEY_PRESSED;
}
}
if (e.getKeyCode() == 27) {
System.exit(0);
}
}
public static void main(String argv[]) {
new Loop1();
}
}