1

I'm doing a little project, its an RPG specifically a 2D Shooter. Somehow I do not know how to make the image move via Keyboard arrow keys. The Image representing the character in the game. If anyone could give me an example on that, I really thank you in advance.

The Only thing i was able to do for now , is make the image im using, MOVE on its own like a SCREEN SAVER. how do I make it move by keyboard arrow keys?

    import java.awt.Graphics2D;
    import java.awt.Graphics;
    import javax.swing.JPanel; 
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent; 
import javax.swing.Timer;

public class gameinsides extends JPanel implements ActionListener {

private Image car; 
private int x=100, y=100;
private Timer t;

public gameinsides(){

    super.setDoubleBuffered(true);
    t = new Timer(7, this);
    t.start();  

}
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    ImageIcon corla = new ImageIcon(this.getClass().getResource("car.png"));
    car = corla.getImage();
    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(car, x, y, this);

}
int xV = 1;
int yV = 1;

public void move(){

    x = x + xV;
    y = y + yV;


}


@Override
public void actionPerformed(ActionEvent e) {
    move();
    //COLLISION FOR LEFT AND RIGHT WALL o A o
    if (x == 0){

        xV = 1;
    } else if ( x == 350 - 50){
        xV = -1;
    }

    //COLLISION FOR TOP AND BOTTOM 
    if (y == 0) {
        yV = 1;
    } else if ( y == 350 ){
        yV = -1;
    }
    repaint();


}

}

jmarkmurphy
  • 11,030
  • 31
  • 59
TheGoldenShinra
  • 31
  • 1
  • 1
  • 4
  • 1
    You need to use [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) or a [key listener](https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html) – Vince Feb 21 '16 at 22:53
  • 1
    [How to use key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Feb 21 '16 at 23:18
  • [For example](http://stackoverflow.com/questions/30494542/how-to-move-a-rectangle-using-keys-in-java/30495246#30495246) – MadProgrammer Feb 21 '16 at 23:22

0 Answers0