Reputation: 848
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?
Upvotes: 3
Views: 1743
Reputation: 133567
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);
Upvotes: 7
Reputation: 452
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.
Upvotes: 2