In my way to build my first game, I’m trying to move my character.
I don’t know if it’s the right way to do it, but basically I’m using a timer inside a run method and the game loop inside the actionlistener.
Even debugging, I don’t know why it doesn’t move.
public synchronized void start (){
running = true;
t1 = new Thread (this);
t1.start();
}
public synchronized void stop (){
running = false;
try {
t1.join();
System.out.println("The game stopped");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//INIT
public Panel(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
addKeyListener(this);
requestFocus();
load();
}
ActionListener gameloop = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
go();
repaint();
System.out.println("The game runs");
}
};
//MAIN PROCESS
public void run(){
Timer timer = new Timer(1000/60,gameloop);
timer.start();
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//PAINT IMAGES
public void paintComponent (Graphics g){
super.paintComponent(g);
g.drawImage(sfondo, 0, 0, this);
g.drawImage(boaris, cordX, cordY, this);
}
//LOADS
public void load (){
try {
String sfondopath = "res/sfondo.png";
sfondo = ImageIO.read(new File (sfondopath));
String imgpath = "res/img.png";
img = ImageIO.read(new File (imgpath));
} catch (IOException e) {
e.printStackTrace();
}
}
public void go(){
cordX += vX;
cordX += vY;
}
public void gameupdate(){
vX=0;
vY=0;
if (down) vY = speed;
if (up) vY = -speed;
if (left) vX = -speed;
if (right) vX = speed;
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
//if the right arrow in keyboard is pressed...
case KeyEvent.VK_RIGHT: {
right = true;
}
break;
//if the left arrow in keyboard is pressed...
case KeyEvent.VK_LEFT: {
left = true;
}
break;
//if the down arrow in keyboard is pressed...
case KeyEvent.VK_DOWN: {
down = true;
}
break;
//if the up arrow in keyboard is pressed...
case KeyEvent.VK_UP: {
up = true;
}
break;
}
gameupdate();
}