我已經開始在java中做一個小遊戲了。就像迷宮一樣。但是我對「敵人」有點問題。同一類型的多個移動對象
我有一個類「球」,創造了一個球員和一個類「敵人」,我想用它來創建多種類型的敵人。敵人是正方形,我需要很多特定的座標所以我必須在廣場向左側移動的同時上下移動球。我不知道這些跡象有多具體。但我只設法創建了一個移動的方形礦石,但是這些礦石不移動。
你們中的任何人可能知道並需要更多的信息,請詢問它,我會發送你的代碼或你需要的東西。 謝謝!
敵對階級:
public class Enemy {
int Y = 20;
private static final int WIDTH = 60;
private static final int HEIGHT = 50;
int x = 1000;
private Game game;
public Enemy(Game game) {
this.game = game;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void move() {
x = x - 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;}
Ball類:
public class Ball {
private static final int DIAMETRU = 30;
int x = 200;
int y = 0;
private Game game;
public Ball(Game game) {
this.game= game;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP)
y = y - 5;
if (e.getKeyCode() == KeyEvent.VK_DOWN)
y = y + 5;
}
public void keyReleased(KeyEvent e) {
}
void move(){
if (collision()){
x = x - 5;
}
if (x == 25)
game.gameOver();
}
private boolean collision() {
return game.enemy.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, DIAMETRU, DIAMETRU);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETRU, DIAMETRU);
}
}
遊戲類
public class Game extends JPanel {
Ball ball = new Ball(this);
GameOver go = new GameOver(this);
Enemy enemy = new Enemy(this);
public Game() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
ball.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
ball.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
enemy.move();
ball.move();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
enemy.paint(g2d);
go.paint(g2d);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Maze");
Game game = new Game();
frame.add(game);
frame.setSize(1000,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(5);
}
}
}
你應該在SO上發佈**相關**代碼片段。其次,你應該問一個具體的問題。 – home
1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)請使用代碼格式化代碼,輸入/輸出和結構化文檔,如HTML或XML。爲此,請選擇樣本並單擊郵件發佈/編輯表單上方的「{}」按鈕。 3)請不要忘記添加'?'提問!有些人在頁面中搜索'?'如果'問題'中不存在,則直接進入下一個(實際)問題。 –
*「這不僅僅是你的需要.THX」*看來你無法知道我們需要什麼來解決這個問題。如果你知道需要什麼,那麼你就有99%的方法可以自己解決問題。另外,停止使用無用的拼寫,如'你'和'thx'。這些不是我們需要在手機上剔除的短信。你有一個完整的鍵盤,用它來達到很好的效果。 –