gpt4 book ai didi

java - 如何使用 drawLine() 获得一条随机方向拍摄的线?

转载 作者:搜寻专家 更新时间:2023-11-01 02:08:54 25 4
gpt4 key购买 nike

我正在做一个有趣的作业,它包括一艘小船,它随着 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;
}


}

提前谢谢你,我已经坚持了很长一段时间了。

滴滴

最佳答案

类似于Snicolas给出的答案:

int x2;
int y2;

//get direction for x cooord
int direction = (int) (Math.random() * 2);

if(direction == 0)
x2 = (int) (300 + Math.random() * applet_width);
else
x2 = ((int) (300 + Math.random() * applet_width)) * -1;


//get direction for the y coord
direction = (int) (Math.random() * 2);

if(direction == 0)
y2 = (int) (300 + Math.random() * applet_width);
else
y2 = ((int) (300 + Math.random() * applet_width)) * -1;


//draw the line
page.drawLine(mouse_x-15, mouse_y-5,x2,y2);

这将创建一条线到一个随机点,该点经过屏幕边缘

关于java - 如何使用 drawLine() 获得一条随机方向拍摄的线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23039472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com