I want to write simple game. Why if I press button UP and RIGHT it not move diogonally, may be it have special code. And how I need to write correctly border and gravity? (Sorry for my English, it is not my home language).
public class Main { public static void main(String args[]) { JFrame frame = new JFrame("Stickman"); Ground ground = new Ground(); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setSize(710, 480); frame.add(ground); frame.setVisible(true); ground.requestFocus(); } }
public class Ground extends JPanel { public Ground() { addKeyListener(new myKeyAdapter()); } Image img = new ImageIcon("Resourse/Untitled.jpg").getImage(); Stickman stk = new Stickman(); private class myKeyAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { stk.keyPressed(e); repaint(); } public void keyReleased(KeyEvent e) { stk.keyReleased(e); repaint(); } } public void paint(Graphics g) { g = (Graphics2D) g; g.drawImage(img, stk.sloi1, 0, null); g.drawImage(stk.img, stk.x, stk.y, null); } }
public class Stickman { public static final int MAX_TOP = (4); public static final int MAX_BOTTOM = (120); Image img = new ImageIcon("Resourse/Untitled2.png").getImage(); int x = 5; int y = 143; int moveAmount = 5; int sloi1 = 0; public void move() { if (y <= MAX_TOP)y = MAX_TOP; if(y >= MAX_BOTTOM)y = MAX_BOTTOM; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_RIGHT) { x += moveAmount; } if (key == KeyEvent.VK_LEFT) { x -= moveAmount; } if (key == KeyEvent.VK_UP) { y -= 20; } } public void keyReleased(KeyEvent e) { } }