Estou criando um jogo simples, estilo zelda (o classico), porém não consigo fazer com o KeyPressed imprima na tela o comando. O código não esta completo eu parei nesse problema e queria resolve-lo antes de continua

  1. Item da lista classe Game

public class Game extends Canvas implements Runnable, KeyListener {

  /**
 * 
 */
private static final long serialVersionUID = 1L;
public static JFrame frame;
  private Thread thread;
  public final int WIDTH = 160;
  public final int  HEIGHT = 120;
  public final int SCALE = 3;
  private boolean isRunning = true;
  
  private BufferedImage image;
  
  public List<Entiti> entities;
  public Spritesheet spritesheet;
  
  private Jogador jogador() {
	return null;
}
  
  
   public Game() {
	   addKeyListener(this);
	   this.setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
	   initFrame();
	   image =  new  BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_BGR);
	   entities = new ArrayList<Entiti>();
	   spritesheet = new Spritesheet("/sprithesheet.png");
	   
	   Jogador jogador = new Jogador (0,0,16,16,spritesheet.getSprite(32,0,16,16));
	   entities.add(jogador);
	   
	    }
   public synchronized void Start(){
	   thread = new Thread(this);
	   isRunning = true;
	   thread.start();
	   
	   
   }
   
   public synchronized void Stop(){
	   isRunning = false;
	   try {
		thread.join();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 	   
	   
   }
   
   public void initFrame() {
	   frame = new JFrame("Game01");
	   frame.add(this);
	   frame.setResizable(false);
	   frame.pack();
	   frame.setLocationRelativeTo(null);
	   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	   frame.setVisible(true);
	   
   }
   
   public static void main (String[]args) {
	   
	   Game game = new Game();
	   game.Start();
	   
   }
   
   public void tick() {
	   for(int i = 0; i <entities.size(); i++) {
	   Entiti e = entities.get(i); 
	   e.tick(e);
	   }   
   }
   public void render() {
	   BufferStrategy bs = this.getBufferStrategy();
	   if(bs == null) {
		   this.createBufferStrategy(3);
		   return;
		   
	   }
	   Graphics g = image.getGraphics();
	   g.setColor(new Color(0,0,0));
	    g.fillRect(0, 0, HEIGHT,WIDTH);
	   
	   for(int i = 0; i <entities.size(); i++) {
	   Entiti e = entities.get(i); 
	   e.render(g);
	   }
	  
	   g.dispose();
	   g = bs.getDrawGraphics();
	   g.drawImage(image,0,0, WIDTH*SCALE,HEIGHT*SCALE,null);
	   bs.show();
	   
   }
   
  public void run(){
	  long lastTime =  System.nanoTime();
	  double amountOfTicks = 60.0;
	  double ns =1000000000 / amountOfTicks;
	  double delta = 0;
	  int frame = 0;
	  double timer = System.currentTimeMillis();
	  while(isRunning) {
		  long now = System.nanoTime();
		  delta +=(now - lastTime ) / ns;
		  lastTime = now;
		  if(delta >= 1) {
			  tick();
			  render();
			  frame ++;
			  delta -- ;
		  }
		  if(System.currentTimeMillis() - timer >= 1000) {
			  System.out.println("FPS" + frame);
			  frame = 0;
			  timer += 1000;
			  
			  
		  }
		  
		  
	  }
	
   }
  
  @Override
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_LEFT) {
			System.out.println("A");
		}else if
			(e.getKeyCode() == KeyEvent.VK_RIGHT){
			System.out.println("D");
				
			}
		 
		
	}
  
@Override
public void keyTyped(KeyEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public void keyReleased(KeyEvent e) {
	// TODO Auto-generated method stub
	
}
  

   
}
  1. Item da lista classe Entiti(era pra ser Entity)

classe Entiti public class Entiti{

private int x;
private int y;
private int width;
private  int height;

private BufferedImage sprite;

public Entiti(int x,int y, int width, int height,BufferedImage sprite) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	this.sprite = sprite;
}


	

public int getX() {
	return this.x;
}
public int getY() {
	return this.y;
}
public int getWidth() {
	return this.width;
}
public int getHeight() {
	return this.height;
}


public void tick() {
}


public void render(Graphics g) {
	g.drawImage(sprite,this.getX(),this.getY(), null);
}




public void tick(Entiti e) {
	// TODO Auto-generated method stub
	
}

}

  1. Item da lista classe Jogador

public class Jogador extends Entiti{

public static boolean RIGHT;

public Jogador(int x, int y, int width, int height, BufferedImage sprite) {
	super(x,y,width,height,sprite);
	
}

}

Tem certeza de que seu Canvas está com o foco quando você pressiona as teclas?

Não, Como assim com foco nas teclas?

Não é foco nas teclas, foco no Canvas.

Para o Canvas responder aos eventos de tecla, ele precisa estar com o foco da janela.

Depois de fazer o frame.setVisible(true), chame o método requestFocus() de seu Canvas.

Ainda não funcionou, eu não consigo nem fazer ele imprimir na tela o KeyPressed.
Tem tempo que estou tentando resolver isso, já fiz e refiz o código 3 vezes vendo a mesma aula mas não consigo achar meu erro.

Se você tirar aqueles ifs, ele imprime algo?

o looping ta imprindo os FPS
image

Mas o looping não tem nada a ver com o keyPressed
Implementa seu keyPressed assim:

public void keyPressed(KeyEvent e) {
	System.out.println("key code: " + e.getKeyCode());
}

Eu consegui fazer ele imprimir com esse método :
image
porém só imprimi mesmo, o jogador na tela não se move mesmo com o requestfocus no Canvas.

O requestFocus não tem nada a ver com o movimento do seu jogador, ele é só entenpara fazer o seu Canvas tratar o pressionamento das teclas, pois um componente visual precisa estar focado para tratar eventos.

Cadê o código que atualiza as coordenadas do seu jogador quando ele se movimenta?
Imagino que isso esteja implementado dentro do método tick do jogador.

1 curtida

image
na classe jogador, estao certos?

Creio que não pois sua classe Jogador estende Entiti e o x e y estão como private na classe Entiti.

não, estão como protected.

Então os códigos postados aqui no fórum estão desatualizados.
Posta os seus fontes atuais, não esqueça de usar o botão de formatação de código: </>

2 curtidas
public class Game extends Canvas implements Runnable, KeyListener {
	
	
	private static final long serialVersionUID = 1L;
	public static JFrame frame;
	  private Thread thread;
	  public final int WIDTH = 160;
	  public final int  HEIGHT = 120;
	  public final int SCALE = 3;
	  private boolean isRunning = true;
	  

	  
	  private BufferedImage image;
	  
	  public List<Entiti> entities;
	  public Spritesheet spritesheet;
	  
	  private Jogador jogador;
	
	  
	  
	   public Game() {
		   addKeyListener(this);	
		   
		   this.setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
		   initFrame();
		   image =  new  BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_BGR);
		   entities = new ArrayList<Entiti>();
		   spritesheet = new Spritesheet("/spritesheet.png");	
		   jogador = new Jogador(0,0,16,16,spritesheet.getSprite(32, 0, 16,16));
		   entities.add(jogador);
		   
		    }
	   public void initFrame() {
		   frame = new JFrame("Game01");
		   frame.add(this);
		   frame.setResizable(false);
		   frame.pack();
		   frame.setLocationRelativeTo(null);
		   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		   frame.setVisible(true);
		   
	   }
	   public synchronized void Start(){
		   thread = new Thread(this);
		   isRunning = true;
		   thread.start();
		   
		   
	   }
	   
       public synchronized void Stop(){
    	   isRunning = false;
    	   try {
			thread.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	 	   
		   
	   }
	   
	  
	   
	   public static void main (String[]args) {
		   
		   Game game = new Game();
		   game.Start();
		   
	   }
	   
	   public void tick() {
		   for(int i = 0; i <entities.size(); i++) {
		   Entiti e = entities.get(i); 
		   e.tick(e);
		   }   
	   }
	   public void render() {
		   BufferStrategy bs = this.getBufferStrategy();
		   if(bs == null) {
			   this.createBufferStrategy(3);
			   return;
			   
		   }
		   Graphics g = image.getGraphics();
		   g.setColor(new Color(0,255,0));
		    g.fillRect(0, 0, WIDTH, HEIGHT);		   
		   for(int i = 0; i <entities.size(); i++) {
		   Entiti e = entities.get(i); 
		   e.render(g);
		   }
		  
		   g.dispose();
		   g = bs.getDrawGraphics();
		   g.drawImage(image,0,0, WIDTH*SCALE,HEIGHT*SCALE,null);
		   bs.show();
		   
	   }
	   
	  public void run(){
		  requestFocus();
		  long lastTime =  System.nanoTime();
		  double amountOfTicks = 60.0;
		  double ns =1000000000 / amountOfTicks;
		  double delta = 0;
		  int frame = 0;
		  double timer = System.currentTimeMillis();
		  while(isRunning) {
			  
			  long now = System.nanoTime();
			  delta +=(now - lastTime ) / ns;
			  lastTime = now;
			  if(delta >= 1) {requestFocus();
				  tick();
				  render();
				  frame ++;
				  delta -- ;
			  }
			   if(System.currentTimeMillis() - timer >= 1000) {
				  System.out.println("FPS" + frame);
				  frame = 0;
				  timer += 1000;
				  
				  
			  }
			  
			  
		  }
		
	   }
	  
	  @Override
		public void keyPressed(KeyEvent e) {
		  switch (e.getKeyCode()) {
          case KeyEvent.VK_RIGHT:
             jogador.right = true;
              System.out.println("Pressed RIGHT");
              break;
          case KeyEvent.VK_LEFT:
                jogador.left = true;
              System.out.println("Pressed LEFT");
              break;
      }
		  switch (e.getKeyCode()) {
          case KeyEvent.VK_UP:
              jogador.right = true;
              System.out.println("Pressed UP");
              break;
          case KeyEvent.VK_DOWN:
              jogador.left = true;
              System.out.println("Pressed DOWN");
              break;
      }
						
		}
	  
	@Override
	public void keyTyped(KeyEvent e) {
		// 
		
	}
	
	@Override
	public void keyReleased(KeyEvent e) {
		//  
		
	}
	  ```
public class Entiti{

	
	
	protected  int x;
	protected int y;
	protected int width;
	protected  int height;
	
	private BufferedImage sprite;
	
	public Entiti(int x,int y, int width, int height,BufferedImage sprite) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.sprite = sprite;
	}
	
	public void setX(int newX) {
		this.x = newX;
	}

	public void setY(int newY) {
		this.x = newY;}
		
	
	public int getX() {
		return this.x;
	}
	public int getY() {
		return this.y;
	}
	public int getWidth() {
		return this.width;
	}
	public int getHeight() {
		return this.height;
	}
	
	
	public void tick() {
	}
	
	
	public void render(Graphics g) {
		g.drawImage(sprite,this.getX(),this.getY(), null);
	}




	public void tick(Entiti e) {
		// TODO Auto-generated method stub
		
	}
	
	
}

public class Jogador extends Entiti{

public boolean right, up, left,down;
public int speed =4;


public Jogador(int x, int y, int width, int height, BufferedImage sprite) {
	super(x,y,width,height,sprite);
	
}
public void tick() {
	if (right) x+=4;
	else if(left) x-=4;
	if (up) y-=4;
	else if (down) y+=4;
	
}
Eu fiz algumas mudanças tentando resolver, porém nada ainda.
1 curtida