我对Java的东西是一个新手,但是..在网上阅读了很多内容之后,我一直在努力开发这款游戏并开始使用,我正在使用一些图片。我想通过KeyListener来更新他们的立场以展示运动的过程,我相信。不幸的是,图像仍然在同一个地方,拒绝移动D:
我确定我对这些代码进行了过度复杂的处理,但是这里是:\
public class Game extends javax.swing.JPanel implements ActionListener, KeyListener{
private Vladimir vlad;
private Timer timer;
public Game() {
addKeyListener(this);
setPreferredSize(new Dimension(1024,768));
setDoubleBuffered(true);
vlad = new Vladimir();
timer = new Timer(15,this);
timer.start();
}
public void actionPerformed (ActionEvent e){
repaint();
}
private void toggleKey(int keyCode, boolean pressed){
if (keyCode == 87){ // W
vlad.move("UP", pressed);
}
if (keyCode == 83){ // S
vlad.move("DOWN", pressed);
}
if (keyCode == 65) // A
{
vlad.move("LEFT", pressed);
}
if (keyCode == 68) // D
{
vlad.move("RIGHT", pressed);
}
}
public void keyPressed(KeyEvent e)
{
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e)
{
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e){
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2d = (Graphics2D)g;
g2d.drawImage(vlad.getGrassMap(),0,0,this);
g2d.drawImage(vlad.getCharOne(),vlad.getX(),vlad.getY(),this);
repaint();
}
}接着..
public class Vladimir{
private int x;
private int y;
private Image grassMapOne;
private Image charOne;
private String gMapLocate = "/phantasma/resources/GrassMap1.png";
private String charOneLocate = "/phantasma/resources/moveright1.png";
public Vladimir(){
ImageIcon gMap1 = new ImageIcon(this.getClass().getResource(gMapLocate));
ImageIcon char1 = new ImageIcon(this.getClass().getResource(charOneLocate));
grassMapOne = gMap1.getImage();
charOne = char1.getImage();
x = 512;
y = 350;
}
public void move(String direction, boolean keyHeld){
if (direction == "UP"){
y += 12;
}
if (direction == "DOWN"){
y -= 12;
}
if (direction == "LEFT"){
x -= 12;
}
if (direction == "RIGHT"){
x += 12;
}
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getGrassMap(){
return grassMapOne;
}
public Image getCharOne(){
return charOne;
}
}