我正在进行一项有趣的任务,其中包括一个小船,该船通过mouseMoved()移动并随机射出激光。我想使用drawLine(mouse_x, mouse_y, ?, ?)绘制激光,但是我无法定义x2和y2的坐标。激光必须横跨屏幕。
这是我目前的情况。
这是我目前的情况。
page.drawLine(mouse_x-15, mouse_y-5,300,300);
当然,我不想让激光一直射向角落(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;
}
}
非常感谢,我已经陷入了相当长时间的困境。
滴滴