我正在做一个小项目,它是一个RPG,特别是2D射击游戏。 不知何故,我不知道如何通过键盘箭头键移动图像。 代表游戏角色的图像。如果有人能给我一个例子,我真的非常感谢你。
我现在唯一可以做的就是让图像使用,像屏幕保护一样自行移动。如何通过键盘箭头键移动?
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();
}
}