import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SpaceInvaders extends JPanel implements ActionListener, KeyListener {
//Declare global variables
private Asteroids asteroid;
private int xDir, yDir;
private Timer t;
private Spaceship ship;
public static void main(String[] args) {
new SpaceInvaders();
}
public SpaceInvaders() {
ship = new Spaceship(600,500, new ImageIcon("ship2.png"));
//Declare and initialize Ball object
asteroid = new Asteroids(100,100, new ImageIcon("Asteroids.png"));
//Initialize the two variables that will determine how many pixels the ball
//will move horizontally and vertically
xDir = 1;
yDir = 3;
//Initialize Timer object and set interval to 50 milliseconds
t = new Timer(20, this);
//Set properties of JPanel object
setLayout(null);
setBackground(Color.BLACK);
addKeyListener(this);
setFocusable(true);
//Declare, initialize and set properties of JFrame
JFrame frame = new JFrame();
frame.setContentPane(this);
frame.setSize(1200,1000);
frame.setTitle("Space Invaders");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Start the timer
t.start();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paintComponent(Graphics g)
{
// Draw the image on the screen
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(asteroid.getImage(), asteroid.getX(), asteroid.getY(),this);
ship.draw(g2);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
Ive tried alot of things and i found no clear answer on the internet, was wondering if i could get some help please. I know that i have to use something relating to cosine and math but i could not come to a conclusion. This is for an asteroid program and has to be able to rotate for the ship to move around the panel.