Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomly angle a line in java?

Tags:

java

graphics

I know where I want the line to start, and I know how long I want to line to be. I want the line to start at co-ordinate 100,100 of a panel and I want it to be 50 px long. How can I randomly angle the line each run? I was thinking something like:

Random rand = new Random(System.currentTimeMillis());
int angle = rand.nextInt % 360;

But how do I now use this to draw the line?

like image 957
Ty_ Avatar asked Nov 23 '25 07:11

Ty_


2 Answers

By passing by polar coordinates you can easily do what you want:

// a random value in [0, 2PI] for the angle in radians
float angle = rand.nextFloat()*2*Math.PI; 
// length of the line
float magnitude = 50.0f;

// start point
Point2D.Float start = new Point2D.Float(100,100);
// end point
Point2D.Float end = new Point2D.Float(start.getX() + Math.cos(angle)*magnitude, start.getY() + Math.sin(angle)*magnitude);
like image 113
Jack Avatar answered Nov 24 '25 23:11

Jack


Once you have the random angle (in radians), you can simply use Math.sin(angle)*length for height of the line, and Math.cos(angle)*length for the width. Finally you can use Grapics drawLine(100,100,width,height) to draw the line.

like image 30
Adam Schmidt Avatar answered Nov 24 '25 23:11

Adam Schmidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!