对于一个学校项目,我正在制作一个tron游戏,我目前正在为自行车使用图片。自行车在屏幕上移动,所以现在我们使用4张不同的图片,这样如果点击一把钥匙转动自行车,那么自行车就会在那时显示一张新图像。现在我只是想找到显示图像的最佳方法,并在点击一个键时将其转动。拥有4个不同的图像或旋转图像会更好吗?请帮助解决这两种情况。
public class contents extends JPanel implements ActionListener, KeyListener
{
private int x = 0, y = 0;
private Timer t;
private ImageIcon d1 = new ImageIcon(this.getClass().getResource("BlueBike.jpg"));
private Image bike1 = d1.getImage();;
private ImageIcon d2 = new ImageIcon(this.getClass().getResource("BlueBike2.jpg"));
private Image bike2 = d2.getImage();;
private ImageIcon d3 = new ImageIcon(this.getClass().getResource("BlueBike3.jpg"));
private Image bike3 = d3.getImage();;
private ImageIcon d4 = new ImageIcon(this.getClass().getResource("BlueBike4.jpg"));
private Image bike4 = d4.getImage();;
private char direction = 'd';
private char newdirection = 'd';
public contents()
{
super.setDoubleBuffered(true);
t = new Timer(7, this);
t.start();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
if (direction == 'r')
g2D.drawImage(bike1, x, y, this);
if (direction == 'l')
g2D.drawImage(bike2, x, y, this);
if (direction == 'u')
g2D.drawImage(bike3, x, y, this);
if (direction == 'd')
g2D.drawImage(bike4, x, y, this);
}
@Override
public void actionPerformed(ActionEvent e)
{
//x=x+1;
direction = newdirection;
repaint();
}
public void keyTyped(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_RIGHT)
{
newdirection = 'r';
}
if (code == KeyEvent.VK_LEFT)
{
newdirection = 'l';
}
if (code == KeyEvent.VK_UP)
{
newdirection = 'u';
}
if (code == KeyEvent.VK_DOWN)
{
newdirection = 'd';
}
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}