我试图用Java制作一种太空入侵者游戏,首先让PNG太空船在屏幕上移动。它似乎应该在哪里,只有它拒绝移动。该程序编译精细,eclipse没有错误/警告。谁能告诉我我做错了什么?
这是我的代码:
import java.awt.*;
import java.net.*;
import java.awt.geom.*;
import java.applet.*;
import java.awt.event.*;
public class DrawImage extends Applet implements KeyListener{
private static final long serialVersionUID = 1L;
private Image image;
private int keycode;
AffineTransform identity = new AffineTransform();
private boolean keyleft = false;
private boolean keyright = false;
private URL getURL(String filename){
URL url = null;
try
{
url = this.getClass().getResource(filename);
}
catch(Exception e)
{
e.printStackTrace();
}
return url;
}
public void init()
{
image = getImage(getURL("spaceship.png"));
addKeyListener(this);
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
//fill background with black
AffineTransform trans = new AffineTransform();
g2d.setColor(Color.GREEN);
g2d.fillRect(0,0,getSize().width,getSize().height);
g2d.drawImage(image,320,240,this);
trans.setTransform(identity);
if(keyright == true)
{
trans.translate(-10,0);
keyleft = false;
}
else if(keyleft == true)
{
trans.translate(10,0);
keyright = false;
}
}
public void keyPressed(KeyEvent e)
{
keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_LEFT)
{
keyleft = true;
}
else if(keycode == KeyEvent.VK_RIGHT)
{
keyright = true;
}
repaint();
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
}
答案 0 :(得分:1)
您应该在paint()方法中将变换设置为g2d:
g2d.setTransform(trans);
所以整个方法是:
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
//fill background with black
AffineTransform trans = new AffineTransform();
g2d.setColor(Color.GREEN);
g2d.fillRect(0,0,getSize().width,getSize().height);
trans.setTransform(identity);
if(keyright == true)
{
trans.translate(-10,0);
keyleft = false;
}
else if(keyleft == true)
{
trans.translate(10,0);
keyright = false;
}
g2d.setTransform(trans);
g2d.drawImage(image,320,240,this);
}