I know the startpoint (the middle of the screen) and the angle (in my example 20°). Now I want to know the position on the edge of the screen, like an invisible line is drawn from the center to the edge in the given angle. For better explanation, I included an image:
Asked
Active
Viewed 1,061 times
2
-
I guess you just need to know the size of the screen, don't you (as well as the absolute coordinates of your known point) ? – Dici Aug 15 '15 at 23:59
-
I can get the height and the width with `getHeight()` and `getWidth()`, so y of my known point is `height / 2` and x is `width / 2`. – Antict Aug 16 '15 at 00:04
-
The unknown point is at x = 0, determining y is just a matter of geometry using the angle. Is this geometry problem your question ? – Dici Aug 16 '15 at 00:06
-
If my angle is, let's say 130°, how do I know whether x or y should be 0? – Antict Aug 16 '15 at 00:14
-
possible duplicate: http://stackoverflow.com/questions/3536428/draw-a-line-at-a-specific-angle-in-java – Theo Aug 16 '15 at 00:42
1 Answers
5
One way to do this is to calculate a point on a circle with a radius equal to or greater than the maximum diagonal, and then just clip it to the screen boundary.
Using Pythagoras' theorem, the length of the maximum diagonal will be
float d = Math.sqrt((width/2)*(width/2) + (height/2)*(height/2));
So you can calculate the point on the circle like this (angle is in radians clockwise from the top):
float x = Math.sin(angle) * d;
float y = -Math.cos(angle) * d;
Then you have to clip the vector from the origin to the point to each of the 4 sides, e.g for the right and left sides:
if(x > width/2)
{
float clipFraction = (width/2) / x; // amount to shorten the vector
x *= clipFraction;
y *= clipFraction;
}
else if(x < -width/2)
{
float clipFraction = (-width/2) / x; // amount to shorten the vector
x *= clipFraction;
y *= clipFraction;
}
Also do this for height/2 and -height/2. Then finally you can add width/2, height/2 to x and y to get the final position (with the center of the screen being width/2, height/2 not 0,0):
x += width/2
y += height/2

samgak
- 23,944
- 4
- 60
- 82
-
I guess this also explains it: http://stackoverflow.com/questions/3536428/draw-a-line-at-a-specific-angle-in-java – Theo Aug 16 '15 at 00:42
-
I tried it, but I think I did something wrong because it isn't working. I pasted my code into the question. – Antict Aug 16 '15 at 01:50
-
You just need to check that your minus signs and comparison operators are correct. I've edited my answer to show clipping for -width/2 – samgak Aug 16 '15 at 01:59
-
1Are you using degrees or radians for the angle? You can convert to radians with Math.toRadians(angle). Also use sin for x and -cos for y to go clockwise from the top – samgak Aug 16 '15 at 03:32