I am trying to use the same enemy class to create two enemies. How can i do this? If I try to just call it twice, it makes two different ones, but they follow the exact same patter.
Here is the class -
package main;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Enemy1 {
int x, y;
int dx, dy;
Image enemy;
boolean starting;
boolean newDirection = false;
public Enemy1()
{
ImageIcon i = new ImageIcon(getClass().getResource("/textures/enemy.png"));
enemy = i.getImage();
x = 100 + (int) (Math.random() * ((200 - 100) + 1));
y = 100 + (int) (Math.random() * ((200 - 100) + 1));
starting = true;
}
public void move()
{
if (starting)
{
int movement = 1 + (int) (Math.random() * ((2 - 1) + 1));
if (movement == 1) dx = 1;
if (movement == 2) dx = -1;
movement = 3 + (int) (Math.random() * ((4 - 3) + 1));
if (movement == 3) dy = 1;
if (movement == 4) dy = -1;
dx = 1;
dy = 1;
starting = false;
}
if (x == 750)
{
x = 749;
newDirection = true;
}
if (x == 10)
{
x = 11;
newDirection = true;
}
if (y == 480)
{
y = 479;
newDirection = true;
}
if (y == 10)
{
y = 11;
newDirection = true;
}
if (newDirection)
{
if ((dx == 1) && (dy == 1))
{
if (y == 479) dy = -1;
if (x == 749) dx = -1;
}
else if ((dx == 1) && (dy == -1))
{
if (y == 11) dy = 1;
if (x == 749) dx = -1;
}
else if ((dx == -1) && (dy == 1))
{
if (y == 479) dy = -1;
if (x == 11) dx = 1;
}
else if ((dx == -1) && (dy == -1))
{
if (y == 11) dy = 1;
if (x == 11) dx = 1;
}
newDirection = false;
}
x = x + dx;
y = y + dy;
}
public int getX() {return x;}
public int getY() {return y;}
public Image getImage() {return enemy;}
}
Here’s the Board class where the enemy is drawn -
public class Board extends JPanel implements ActionListener
{
private static final long serialVersionUID = -6045447081410695806L;
Player p;
Enemy1 en, en2;
Image background;
Timer time;
Player playerGetX;
public Board()
{
p = new Player();
en = new Enemy1();
en2 = new Enemy1();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon(getClass().getResource("/textures/Moldy_Background.png"));
background = i.getImage();
time = new Timer(5, this);
time.start();
}
public void actionPerformed(ActionEvent e)
{
p.move();
en.move();
en2.move();
checkCollision();
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(background, 0, 0, null);
g2d.drawImage(p.getImage(), p.getX(), p.getY(), null);
g2d.drawImage(en.getImage(), en.getX(), en.getY(), null);
g2d.drawImage(en2.getImage(), en2.getX(), en2.getY(), null);
}
private class AL extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
p.keyReleased(e);
}
public void keyPressed(KeyEvent e)
{
p.keyPressed(e);
}
}
public void checkCollision()
{
}
}
Thanks.