Hello every1,
I am makeing a java 2D game and i cant figure out how to add the wasd movement. I allready made a keyboard (wich is called "Keyboard") reader class but idk where do i add the key listener (addKeyListener(new Keyboard)) !
So here is all my code:
MainClass:
import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; public class MainClass extends JFrame{ private Sprite sprite; private Screen s; private Image bg; private Image pic; private Image pic2; private Animation a; private Keyboard k; public boolean running = true; public static void main(String[] args){ MainClass m = new MainClass(); m.run(); } private static final DisplayMode modes[] = { new DisplayMode(1920,1080,32,0), new DisplayMode(1920,1080,64,0), new DisplayMode(1920,1080,24,0), new DisplayMode(1920,1080,16,0), new DisplayMode(640,480,32,0), new DisplayMode(640,480,24,0), new DisplayMode(640,480,16,0), new DisplayMode(640,480,64,0), }; public void run(){ s = new Screen(); try{ DisplayMode dm = s.findFirstCompatibleDisplayMode(modes); s.setFullScreen(dm); loadpics(); movieLoop(); }finally{ s.restoreScreen(); } } public void loadpics() { bg = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\BG.png").getImage(); pic = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\Face.png").getImage(); pic2 = new ImageIcon("C:\\Users\\Sasha\\Desktop\\GameDev\\Face2.png").getImage(); a=new Animation(); a.addScene(pic, 100); a.addScene(pic2, 100); sprite = new Sprite(a); sprite.setVelocityX(0.5f); sprite.setVelocityY(0.5f); } public void movieLoop(){ long startingTime = System.currentTimeMillis(); long cumTime = startingTime; while(running){ long timePassed = System.currentTimeMillis() - cumTime; cumTime+=timePassed; update(timePassed); Graphics2D g = s.getGraphics(); draw(g); g.dispose(); s.update(); try{ Thread.sleep(20); }catch(Exception ex){} } } public void draw(Graphics g){ g.drawImage(bg, 0, 0, null); g.drawImage(sprite.getImage(),Math.round(sprite.getXPos()),Math.round(sprite.getYPos()),null); } public void update(long timePassed){ if(sprite.getXPos() < 0){ sprite.setVelocityX(Math.abs(sprite.getVelocityX())); }else if (sprite.getXPos() + sprite.getWidth() >= s.getWidth()){ sprite.setVelocityX(-Math.abs(sprite.getVelocityX())); } if(sprite.getYPos() < 0){ sprite.setVelocityY(Math.abs(sprite.getVelocityY())); }else if (sprite.getYPos() + sprite.getHeight() >= s.getHeight()){ sprite.setVelocityY(-Math.abs(sprite.getVelocityY())); } sprite.update(timePassed); sprite.move(); } public class TAdapter{ public void keyPressed(KeyEvent e){ k.keyPressed(e); } public void keyReleased(KeyEvent e){ k.keyReleased(e); } } }
Sprite class:
import java.awt.Image; import java.awt.MouseInfo; import java.awt.Window; import java.awt.event.*; public class Sprite { private Animation a; private float x; private float y; private float velocityX; private float velocityY; private Keyboard k; private Screen s; private MainClass m; public Sprite(Animation a){ this.a = a; } public void update(long timePassed){ a.update(timePassed); } public void move(){ x += velocityX; y += velocityY; } public void keyReleased(KeyEvent e){ int KeyCode =e.getKeyCode(); if(KeyCode == KeyEvent.VK_W){ setVelocityY(0); } if(KeyCode == KeyEvent.VK_S){ setVelocityY(0); } if(KeyCode == KeyEvent.VK_A){ setVelocityX(0); } if(KeyCode == KeyEvent.VK_D){ setVelocityX(0); } } public float getXPos(){ return x; } public float getYPos(){ return y; } public void setXPos(float x){ this.x = x; } public void setYPos(float y){ this.y = y; } public int getWidth(){ return a.getImage().getWidth(null); } public int getHeight(){ return a.getImage().getHeight(null); } public float getVelocityX(){ return velocityX; } public float getVelocityY(){ return velocityY; } public void setVelocityX(float velocityX){ this.velocityX = velocityX; } public void setVelocityY(float velocityY){ this.velocityY = velocityY; } public Image getImage(){ return a.getImage(); } }
Animation class:
import java.awt.Image; import java.util.ArrayList; public class Animation { private ArrayList scenes; private int sceneIndex; private long movieTime; private long totalTime; public Animation(){ scenes = new ArrayList(); totalTime = 0; start(); } public synchronized void addScene(Image i, long t){ totalTime+=t; scenes.add(new OneScene (i, totalTime)); } public synchronized void start(){ movieTime=0; sceneIndex=0; } public synchronized void update(long timePassed){ if(scenes.size()>1){ movieTime+=timePassed; if(movieTime >= totalTime){ movieTime=0; sceneIndex=0; } while(movieTime >getScene(sceneIndex).endTime){ sceneIndex++; } } } public synchronized Image getImage(){ if(scenes.size()==0){ return null; }else{ return getScene(sceneIndex).pic; } } private OneScene getScene(int x){ return (OneScene)scenes.get(x); } public class OneScene{ Image pic; long endTime; private OneScene(Image pic, long endTime){ this.pic = pic; this.endTime = endTime; } } }
Screen class(wich i dought you will need, but its good to have it =) ):
import java.awt.*; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.lang.reflect.InvocationTargetException; import javax.swing.JFrame; public class Screen { private GraphicsDevice vc; public Screen(){ GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); vc = env.getDefaultScreenDevice(); } public DisplayMode[] getCompatibleDisplayModes(){ return vc.getDisplayModes(); } public DisplayMode findFirstCompatibleDisplayMode(DisplayMode modes[]){ DisplayMode goodModes[] = vc.getDisplayModes(); for(int i=0;i<modes.length;i++){ for(int j=0;j<goodModes.length;j++){ if(displayModesMatch(modes[i],goodModes[j])){ return modes[i]; } } } return null; } public DisplayMode getCurrentDisplayMode(){ return vc.getDisplayMode(); } public boolean displayModesMatch(DisplayMode m1,DisplayMode m2){ if(m1.getWidth() != m1.getWidth() || m1.getHeight() != m2.getHeight()){ return false; } if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){ return false; } if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){ return false; } return true; } public void setFullScreen(DisplayMode dm){ JFrame f = new JFrame(); f.setUndecorated(true); f.setResizable(false); f.setIgnoreRepaint(true); vc.setFullScreenWindow(f); if(dm != null && vc.isDisplayChangeSupported()){ try{ vc.setDisplayMode(dm); }catch(Exception ex){} } f.createBufferStrategy(3); } public Graphics2D getGraphics(){ Window w = vc.getFullScreenWindow(); if(w != null){ BufferStrategy b = w.getBufferStrategy(); return(Graphics2D)b.getDrawGraphics(); } else{ return null; } } public void update(){ Window w = vc.getFullScreenWindow(); if(w != null){ BufferStrategy b = w.getBufferStrategy(); if(!b.contentsLost()){ b.show(); } } } public Window getFullScreenWindow(){ return vc.getFullScreenWindow(); } public int getWidth(){ Window w = vc.getFullScreenWindow(); if(w != null){ return w.getWidth(); }else{ return 0; } } public int getHeight(){ Window w = vc.getFullScreenWindow(); if(w != null){ return w.getHeight(); }else{ return 0; } } public void restoreScreen(){ Window w = vc.getFullScreenWindow(); if(w != null){ w.dispose(); } vc.setFullScreenWindow(null); } public BufferedImage createCompatibleImage(int w,int h,int t){ Window win = vc.getFullScreenWindow(); if(win !=null){ GraphicsConfiguration gc = win.getGraphicsConfiguration(); return gc.createCompatibleImage(w,h,t); }else{ return null; } } }
And finally, the Keyboard class:
import java.awt.Graphics2D; import java.awt.Window; import java.awt.event.*; public class Keyboard extends MainClass{ private Sprite sprite; private Screen s; private Keyboard k; private MainClass m; public void keyPressed(KeyEvent e){ int KeyCode = e.getKeyCode(); if(KeyCode == KeyEvent.VK_W){ sprite.setVelocityY(1); } if(KeyCode == KeyEvent.VK_S){ sprite.setVelocityY(-1); } if(KeyCode == KeyEvent.VK_A){ sprite.setVelocityX(1); if(KeyCode == KeyEvent.VK_D){ sprite.setVelocityX(-1); } if(KeyCode == KeyEvent.VK_ESCAPE){ m.running = false; } } } public void keyReleased(KeyEvent e){ int KeyCode =e.getKeyCode(); if(KeyCode == KeyEvent.VK_W){ sprite.setVelocityY(0); } if(KeyCode == KeyEvent.VK_S){ sprite.setVelocityY(0); } if(KeyCode == KeyEvent.VK_A){ sprite.setVelocityX(0); if(KeyCode == KeyEvent.VK_D){ sprite.setVelocityX(0); } e.consume(); } } public void keyTyped(KeyEvent e){ e.consume(); } public void draw(Graphics2D g){ super.draw(g); } }
plz help me!