我正在尝试建立塔防游戏。现在我已经完成了类Map(带有怪物通过路径的地图)和Creep类(通过地图的怪物)。
creep对象应位于地图对象的顶部。但是蠕变对象现在正在地图后面移动并且完全不可见。我试图在类Creep的paintComponent()中改变g.fillOval()的参数,我确信蠕变正在落后。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test2
{
public static void main(String[] args)
{
JFrame frame = new JFrame("TEST_MAP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(){
public boolean isOptimizedDrawingEnabled(){
return false;
}
};
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
Map testMap = new Map();
panel.add(testMap);
Creep red = new Creep(testMap);
panel.add(red);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
class Map extends JComponent
{
static final int largeGrid = 50;
int[][] path = new int[2][];
public Map()
{
path[0] = new int[] {0, 2, 2, 5, 5, 7};
path[1] = new int[] {1, 1, 6, 6, 2, 2};
}
public void paintComponent(Graphics g)
{
g.setColor(Color.GRAY);
for(int i = 0; i < 6 - 1; i++)
{
if(path[0][i] == path[0][i + 1]) //Vertical
g.fillRect(
Math.min(path[0][i], path[0][i + 1]) * largeGrid - largeGrid / 2,
Math.min(path[1][i], path[1][i + 1]) * largeGrid - largeGrid / 2,
largeGrid,
Math.abs(line(i)[2] - line(i)[1]) * largeGrid + largeGrid);
else //Horizontal
g.fillRect(
Math.min(path[0][i], path[0][i + 1]) * largeGrid - largeGrid / 2,
Math.min(path[1][i], path[1][i + 1]) * largeGrid - largeGrid / 2,
Math.abs(line(i)[2] - line(i)[1]) * largeGrid + largeGrid,
largeGrid);
}
}
public int[] line(int i)
{
int[] temp = new int[3];
if(path[0][i] == path[0][i + 1])
{
temp[0] = path[0][i]; //Longitudinal coordinate
temp[1] = path[1][i];
temp[2] = path[1][i + 1];
} else
{
temp[0] = path[1][i];
temp[1] = path[0][i];
temp[2] = path[0][i + 1];
}
return temp;
}
}
class Creep extends JComponent implements Runnable
{
public static final int diameter = 30;
int hp, speed, posX, posY;
Thread t = new Thread(this);
Map m;
public Creep(Map m)
{
this.m = m;
posX = m.path[0][0] * Map.largeGrid;
posY = m.path[1][0] * Map.largeGrid;
t.start();
}
public Creep(int hp, int speed, Map m)
{
this(m);
this.hp = hp;
this.speed = speed;
}
public void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.fillOval(posX - diameter / 2, posY - diameter / 2, diameter, diameter);
}
public void walk() throws InterruptedException
{
for(int i = 0; i < m.path[0].length - 1; i++)
{
if(m.path[0][i] == m.path[0][i + 1]) //Vertical
{
while(posY != m.path[1][i + 1] * Map.largeGrid)
{
if(m.path[1][i] < m.path[1][i + 1])
posY++;
else
posY--;
repaint();
t.sleep(5);
}
} else //Horizontal
{
while(posX != m.path[0][i + 1] * Map.largeGrid)
{
if(m.path[0][i] < m.path[0][i + 1])
posX++;
else
posX--;
repaint();
t.sleep(5);
}
}
}
}
public void run()
{
try
{
walk();
} catch(InterruptedException ie)
{
}
}
}