I have a game in which two ellipses appear on a JFrame, one controlled by the a - s - d - w keys and the other one controlled by the arrow keys. Here is my run method:
public void run() {
while (animator != null) {
repaint();
player1.move(player1.direction);
player2.move(player2.direction);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
Here is my individual player classes. This is the paintComponent method of the player 1 class. (Player 1 and Player 2 are identical) The variables shape, xPos, yPos, size, and Color are all fine. (They are attached to values)
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
switch(Shape) {
case 1: Ellipse2D.Double ball = new Ellipse2D.Double(xPos, yPos, size, size);
g2.setPaint(Color);
g2.draw(ball);
g2.fill(ball);
break;
case 2: Rectangle2D.Double rectangle = new Rectangle2D.Double(xPos, yPos, size, size);
g2.setPaint(Color);
g2.draw(rectangle);
g2.fill(rectangle);
break;
}
}
I control the direction of the ellipses through the use of a class called KeyController. Here is a sample part of that program; The rest is the same (Remember that is just an excerpt):
public void keyPressed(KeyEvent e) {
// Player 1 Left
if(e.getKeyCode() == KeyEvent.VK_A){
Player1.setDirection(270);
System.out.println("A pressed");
}
// Player 1 Down
if(e.getKeyCode() == KeyEvent.VK_S){
Player1.setDirection(180);
System.out.println("S pressed");
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
Player2.setDirection(270);
System.out.println("LEFT pressed");
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
Player2.setDirection(180);
System.out.println("DOWN pressed");
}
The rest of the program runs fine. (It has a keyTyped and a keyPressed)
Now my question is that when I run my program, I see one ellipse and all keys can control it, both the a - s - d - w keys and the arrow keys.
If you need more code, just ask me. (I have a main method and it works fine.)
How to make Ellipse respond to controls?