我在使用图像而不是矢量图形开发我的第一个 Java 游戏时遇到了一些麻烦。目前我正在尝试使用对象在按键上移动图像AffineTransform
。只是它不会动。我究竟做错了什么?我还没有尝试过使用线程,但我不知道该怎么做。如果您认为这会有所帮助,请将其包含在您的答案中。
这是我的代码:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.applet.*;
public class DisplayImage extends Applet implements KeyListener{
AffineTransform identity = new AffineTransform();
boolean left = false;
boolean right = false;
public URL getURL(String filename)
{
URL url = null;
try
{
url = this.getClass().getResource(filename);
}
catch(Exception e){e.printStackTrace();}
return url;
}
private Image image;
public void init()
{
image = getImage(getURL("spaceship.png"));
addKeyListener(this);
}
public void update(Graphics g){paint(g);}
public void paint(Graphics g)
{
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,getSize().width,getSize().height);
if(left==true)
{
trans.translate(-10,0);
left = false;
repaint();
}
if(right==true)
{
trans.translate(10,0);
right = false;
repaint();
}
g2d.drawImage(image,0,0,this);
}
public void keyPressed(KeyEvent e)
{
int keycode = e.getKeyCode();
switch(keycode)
{
case KeyEvent.VK_RIGHT:
right = true;
repaint();
case KeyEvent.VK_LEFT:
left = true;
repaint();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
}
有人可以评论或回答吗?我觉得一个“风滚草”徽章正朝着我的方向前进。