I'm working on a fun assignment that consists of a little ship that moves with the mouseMoved() and shoots laser beam in random directions. I want to use drawLine(mouse_x, mouse_y, ?, ?)for the laser but I can't define the coordinates of x2 and y2. The laser has to cross the screen.
This is what I have so far. page.drawLine(mouse_x-15, mouse_y-5,300,300);
of course I don't want the laser to keep shooting at the corner (300,300).
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SpaceShip extends Applet
implements MouseListener, MouseMotionListener {
private int applet_width = 300; //width of applet
private int applet_height =300; //height of applet
private int mouse_x, mouse_y; // the mouse coordinates
private int shots = 0; //count of shots
private boolean buttonPressed = false;
//init()
public void init() {
setSize(applet_width, applet_height); //set size of applet
setBackground( Color.black ); //set color of background
mouse_x = applet_width/2; //initiate mouse in the middle of the applet
mouse_y = applet_height/2;
addMouseListener( this ); //adding mouse listener
addMouseMotionListener( this ); // adding motion listener
}
// Drawing of the spaceship and laser beam
public void paint( Graphics page ) {
page.setColor(colorRand()); // random color laser beam
page.drawLine(mouse_x-15, mouse_y-5,300,300);
page.setColor( Color.YELLOW );//yellow spaceship
page.fillOval( mouse_x-30, mouse_y-15, 60, 30 );
}
public void mouseEntered( MouseEvent e ) {
}
public void mouseExited( MouseEvent e ) {
}
public void mouseClicked( MouseEvent e ) {
shots++;
showStatus("Number of shots: " + shots);
}
public void mousePressed( MouseEvent e ) {
buttonPressed = true;
repaint();
}
public void mouseReleased( MouseEvent e ) {
buttonPressed = false;
setBackground( Color.black );
repaint();
}
public void mouseMoved( MouseEvent e ) {
mouse_x = e.getX();
mouse_y = e.getY();
repaint();
}
public void mouseDragged( MouseEvent e ) {
}
//method generating a random color RGB
public Color colorRand(){
int r = (int)(Math.random()*256);
int g = (int)(Math.random()*256);
int b = (int)(Math.random()*256);
Color randomColor = new Color(r,g,b);
return randomColor;
}
}
Thank you in advance, I've been stuck on this for quite a while now.
Didi