这是我第一次尝试在java中创建一个2D游戏时,我制作了一个8位的小角色,我想用它代替屏幕上出现的矩形。我无法理解如何将.png图像放入矩形的位置,或者我将如何制作角色,在这种情况下,将图像保存到我的硬盘中。谢谢!
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Keying extends JPanel {
public Rectangle character;
public int charW = 24;
public int charH = 36;
public boolean right = false;
public boolean left = false;
public boolean up = false;
public boolean down = false;
public Keying(Display f, Images i)
{
character = new Rectangle(180, 180, charW, charH);
f.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_D)
{
right = true;
}
if (e.getKeyCode() == KeyEvent.VK_A)
{
left = true;
}
if (e.getKeyCode() == KeyEvent.VK_S)
{
down = true;
}
if (e.getKeyCode() == KeyEvent.VK_W)
{
up = true;
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_D)
{
right = false;
}
if (e.getKeyCode() == KeyEvent.VK_A)
{
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_S)
{
down = false;
}
if (e.getKeyCode() == KeyEvent.VK_W)
{
up = false;
}
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.white);
g.setColor(Color.black);
g.fillRect(character.x, character.y, character.width, character.height);
if (right)
{
character.x += 1;
}
if (left)
{
character.x -= 1;
}
if (down)
{
character.y += 1;
}
if (up)
{
character.y -= 1;
}
repaint();
}
}
答案 0 :(得分:1)
这个过程相对简单......
首先加载角色图片......
public class Keying extends JPanel {
//public Rectangle character;
private java.awt.BufferedImage character;
private java.awt.Point characterLocation;
//...
public Keying(Display f, Images i) throws IOException
{
character = javax.ImageIO.read(...);
characterLocation = new Point(0, 0);
//...
有关详细信息,请参阅Reading/Loading an Image ...
然后,您只想绘制character
图像...
@Override
protected void paintComponent(Graphics g)
{
g.drawImage(character, characterLocaiton.x, characterLocation.y, this);
<强>建议强>
KeyListener
,它很容易出现你真正不想处理的焦点问题。而是使用键绑定,有关详细信息,请参阅How to Use Key Bindings setBackground
(当您调用此内容时,背景已经被绘制)或repaint