java find intersection of Line and Rectangle - java

So, i am programming a small game.
As the player, you fly a spaceship in 2d space.
I want to have a marker that points at a selected Object like a sun or a planet, if selected in the scanner.
Everything of that works fine except the drawing of the Marker at the screen border.
Here is my programm so far:
i first painted a Marker
Marker
In order to rotate the Marker, to let it point in direction of the object which is out of the screen, i use this Algorythm.
double Marker_vec = Math.toDegrees(Vector2F.getAngle( SolarSystem.object_vectors[marker],center,player.pos));
public static double getAngle(Vector2F v1, Vector2F v2, Vector2F fixed)
{
double angle1 = Math.atan2(v1.ypos - fixed.ypos, v1.xpos - fixed.xpos);
double angle2 = Math.atan2(v2.ypos - fixed.ypos, v2.xpos - fixed.xpos);
return angle1 - angle2;
}
Basically what i do is this, take a fixed point on the left side of the screen, the fixed point of the Players ship and the Object and get the Angle inbetween those two lines.
The resulting value is the degrees i have to turn my marker in.
And that works fine
Get angle
My problem is to display it on the edge of the screen.
My attempt to do so is that i create a Rectangle that fits the Screen:
screen_rec = new Rectangle(0,0,Main.width-1,Main.height-1);
Then i cut used the rectangles values of X,Y, width and height to create 4 Lines which together form the Rectangle around the screen.
Now i want to see if a line, drawn between the player and the selected Object intersects with any of the lines of the rectangle and get that point.
And finally display the rotated markerimage at those coordinates.
Here is my Code for that
marker_vec = Vector2F.getIntersectionPoint(line, Player.screen_rec);
public static Point intersection(Line2D lineA, Line2D lineB)
{
double x1 = lineA.getX1();
double y1 = lineA.getY1();
double x2 = lineA.getX2();
double y2 = lineA.getY2();
double x3 = lineB.getX1();
double y3 = lineB.getY1();
double x4 = lineB.getX2();
double y4 = lineB.getY2();
double d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
if (d == 0) return null;
double xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
double yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;
return new Point((int)xi,(int)yi);
}
public static Point[] getIntersectionPoint(Line2D line, Rectangle2D rectangle) {
Point[] p1 = new Point[4];
// Top line
p1[0] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY()));
// Bottom line
p1[1] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY() + rectangle.getHeight(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY() + rectangle.getHeight()));
// Left side...
p1[2] = intersection(line,
new Line2D.Double(
rectangle.getX(),
rectangle.getY(),
rectangle.getX(),
rectangle.getY() + rectangle.getHeight()));
// Right side
p1[3] = intersection(line,
new Line2D.Double(
rectangle.getX() + rectangle.getWidth(),
rectangle.getY(),
rectangle.getX() + rectangle.getWidth(),
rectangle.getY() + rectangle.getHeight()));
return p1;
}
But somehow the Marker is displayed only at the upper and left sceenside.
I tried to solve it by subtracting the width in the xaxis in the drawing function, but that didnt work.
And those lines shouldnt have any intersectionpoints anyways, because the line between the player and the object does not intersect that rectangleline.
I will post images of how it looks in the comments
I just tried for serveral days and cant find any solution.
Thanks in advance
Spytrycer

I solved it. I got rid of the line:
if (d == 0) return null;
And the While where i drew the Markers was not going long enough.
Plus, i surrounded the draw functions with if and made sure the markers are only shown when the Angle is a specific value.

Related

Java Swing - Calculating what angle the mouse position is to the center of the screen

I'm making a 2D topdown view shooter game with Java Swing. I want to calculate what angle the mouse pointer is compared to the center of the screen so some of my Sprites can look toward the pointer and so that I can create projectiles described by an angle and a speed. Additionally If the pointer is straight above the middle of the screen, I want my angle to be 0°, if straight to its right, 90°, if straight below 180°, and straight left 270°.
I have made a function to calculate this:
public static float calculateMouseToPlayerAngle(float x, float y){
float mouseX = (float) MouseInfo.getPointerInfo().getLocation().getX();
float mouseY = (float)MouseInfo.getPointerInfo().getLocation().getY();
float hypotenuse = (float) Point2D.distance(mouseX, mouseY, x, y);
return (float)(Math.acos(Math.abs(mouseY-y)/hypotenuse)*(180/Math.PI));
}
The idea behind it is that I calculate the length of the hypotenuse then the length of the side opposite of the angle in question. The fraction of the 2 should be a cos of my angle, so taking that result's arc cos then multiplying that by 180/Pi should give me the angle in degrees. This does work for above and to the right, but straight below returns 0 and straight left returns 90. That means that I currently have 2 problems where the domain of my output is only [0,90] instead of [0,360) and that it's mirrored through the y (height) axis. Where did I screw up?
You can do it like this.
For a window size of 500x500, top left being at point 0,0 and bottom right being at 500,500.
The tangent is the change in Y over the change in X of two points. Also known as the slope it is the ratio of the sin to cos of a specific angle. To find that angle, the arctan (Math.atan or Math.atan2) can be used. The second method takes two arguments and is used below.
BiFunction<Point2D, Point2D, Double> angle = (c,
m) -> (Math.toDegrees(Math.atan2(c.getY() - m.getY(),
c.getX() - m.getX())) + 270)%360;
BiFunction<Point2D, Point2D, Double> distance = (c,
m) -> Math.hypot(c.getY() - m.getY(),
c.getX() - m.getX());
int screenWidth = 500;
int screenHeight = 500;
int ctrY = screenHeight/2;
int ctrX = screenWidth/2;
Point2D center = new Point2D.Double(ctrX,ctrY );
Point2D mouse = new Point2D.Double(ctrX, ctrY-100);
double straightAbove = angle.apply(center, mouse);
System.out.println("StraightAbove: " + straightAbove);
mouse = new Point2D.Double(ctrX+100, ctrY);
double straightRight = angle.apply(center, mouse);
System.out.println("StraightRight: " + straightRight);
mouse = new Point2D.Double(ctrX, ctrY+100);
double straightBelow = angle.apply(center, mouse);
System.out.println("StraightBelow: " + straightBelow);
mouse = new Point2D.Double(ctrX-100, ctrY);
double straightLeft = angle.apply(center, mouse);
System.out.println("Straightleft: " + straightLeft);
prints
StraightAbove: 0.0
StraightRight: 90.0
StraightBelow: 180.0
Straightleft: 270.0
I converted the radian output from Math.atan2 to degrees. For your application it may be more convenient to leave them in radians.
Here is a similar Function to find the distance using Math.hypot
BiFunction<Point2D, Point2D, Double> distance = (c,m) ->
Math.hypot(c.getY() - m.getY(),
c.getX() - m.getX());

Connect two circles with a line

I'm drawing two shapes (circles) in a JPanel and I need to connect them with a line. I was doing this by just getting the middle point of the circle and connecting each other, easy.
The problem is that now I need to make single-direction lines, which has an "arrow" at the end, to point out which direction the line goes. So now I can't use the middle point of the circle because I need to connect each other from border to border, so the "arrow' can appear correctly.
On my last try that was the result, nothing good:
PS: In the screenshot I'm not filling the circles just to see the exact position of the line, but normally I would fill it.
I'm having trouble to calculate the exact position of the border I need to start/end my line. Anyone has any idea on how to do this?
EDIT: The circles are movable, they could be in any position, so the line should work in any case.
Okay, so basically, we can break down the problem to basic issues:
Get the angle between the two circles
Draw a line from circumference of one circle to another along this angle
Both these issues aren't hard to solve (and any time spent searching the internet would provide solutions - because that's where I got them from ;))
So, the angle between two points could be calculated using something like...
protected double angleBetween(Point2D from, Point2D to) {
double x = from.getX();
double y = from.getY();
// This is the difference between the anchor point
// and the mouse. Its important that this is done
// within the local coordinate space of the component,
// this means either the MouseMotionListener needs to
// be registered to the component itself (preferably)
// or the mouse coordinates need to be converted into
// local coordinate space
double deltaX = to.getX() - x;
double deltaY = to.getY() - y;
// Calculate the angle...
// This is our "0" or start angle..
double rotation = -Math.atan2(deltaX, deltaY);
rotation = Math.toRadians(Math.toDegrees(rotation) + 180);
return rotation;
}
And the point on a circle can be calculated using something like...
protected Point2D getPointOnCircle(Point2D center, double radians, double radius) {
double x = center.getX();
double y = center.getY();
radians = radians - Math.toRadians(90.0); // 0 becomes the top
// Calculate the outter point of the line
double xPosy = Math.round((float) (x + Math.cos(radians) * radius));
double yPosy = Math.round((float) (y + Math.sin(radians) * radius));
return new Point2D.Double(xPosy, yPosy);
}
Just beware, there's some internal modifications of the results to allow for the difference between the mathematical solution and the way that the Graphics API draws circles
Okay, so big deal you say, how does that help me? Well, I great deal actually.
You'd calculate the angle between the to circles (both to and from, you might be able to simple inverse one angle, but I have the calculation available so I used it). From that, you can calculate the point on each circle where the line will intersect and then you simply need to draw it, something like...
double from = angleBetween(circle1, circle2);
double to = angleBetween(circle2, circle1);
Point2D pointFrom = getPointOnCircle(circle1, from);
Point2D pointTo = getPointOnCircle(circle2, to);
Line2D line = new Line2D.Double(pointFrom, pointTo);
g2d.draw(line);
Runnable Example
Because I've distilled much of the calculations down to communalised properties, I've provided my test code as a runnable example. All the calculations are based on dynamic values, nothing is really hard coded. For example, you can change the size and positions of the circles and the calculations should continue to work...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Ellipse2D circle1;
private Ellipse2D circle2;
private Point2D drawTo;
public TestPane() {
circle1 = new Ellipse2D.Double(10, 10, 40, 40);
circle2 = new Ellipse2D.Double(100, 150, 40, 40);
//addMouseMotionListener(new MouseAdapter() {
// #Override
// public void mouseMoved(MouseEvent e) {
// drawTo = new Point2D.Double(e.getPoint().x, e.getPoint().y);
// repaint();
// }
//});
}
protected Point2D center(Rectangle2D bounds) {
return new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
}
protected double angleBetween(Shape from, Shape to) {
return angleBetween(center(from.getBounds2D()), center(to.getBounds2D()));
}
protected double angleBetween(Point2D from, Point2D to) {
double x = from.getX();
double y = from.getY();
// This is the difference between the anchor point
// and the mouse. Its important that this is done
// within the local coordinate space of the component,
// this means either the MouseMotionListener needs to
// be registered to the component itself (preferably)
// or the mouse coordinates need to be converted into
// local coordinate space
double deltaX = to.getX() - x;
double deltaY = to.getY() - y;
// Calculate the angle...
// This is our "0" or start angle..
double rotation = -Math.atan2(deltaX, deltaY);
rotation = Math.toRadians(Math.toDegrees(rotation) + 180);
return rotation;
}
protected Point2D getPointOnCircle(Shape shape, double radians) {
Rectangle2D bounds = shape.getBounds();
// Point2D point = new Point2D.Double(bounds.getX(), bounds.getY());
Point2D point = center(bounds);
return getPointOnCircle(point, radians, Math.max(bounds.getWidth(), bounds.getHeight()) / 2d);
}
protected Point2D getPointOnCircle(Point2D center, double radians, double radius) {
double x = center.getX();
double y = center.getY();
radians = radians - Math.toRadians(90.0); // 0 becomes th?e top
// Calculate the outter point of the line
double xPosy = Math.round((float) (x + Math.cos(radians) * radius));
double yPosy = Math.round((float) (y + Math.sin(radians) * radius));
return new Point2D.Double(xPosy, yPosy);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.draw(circle1);
g2d.draw(circle2);
// This was used for testing, it will draw a line from circle1 to the
// drawTo point, which, if enabled, is the last known position of the
// mouse
//if (drawTo != null) {
// Point2D pointFrom = center(circle1.getBounds2D());
// g2d.setColor(Color.RED);
// g2d.draw(new Line2D.Double(drawTo, pointFrom));
//
// double from = angleBetween(pointFrom, drawTo);
// System.out.println(NumberFormat.getNumberInstance().format(Math.toDegrees(from)));
//
// Point2D poc = getPointOnCircle(circle1, from);
// g2d.setColor(Color.BLUE);
// g2d.draw(new Line2D.Double(poc, drawTo));
//}
double from = angleBetween(circle1, circle2);
double to = angleBetween(circle2, circle1);
Point2D pointFrom = getPointOnCircle(circle1, from);
Point2D pointTo = getPointOnCircle(circle2, to);
g2d.setColor(Color.RED);
Line2D line = new Line2D.Double(pointFrom, pointTo);
g2d.draw(line);
g2d.dispose();
}
}
}
Arrow head
The intention is to treat the arrow head as a separate entity. The reason is because it's just simpler that way, you also get a more consistent result regardless of the distance between the objects.
So, to start with, I define a new Shape...
public class ArrowHead extends Path2D.Double {
public ArrowHead() {
int size = 10;
moveTo(0, size);
lineTo(size / 2, 0);
lineTo(size, size);
}
}
Pretty simple really. It just creates two lines, which point up, meeting in the middle of the available space.
Then in the paintComponent method, we perform some AffineTransform magic using the available information we already have, namely
The point on our target circles circumference
The angle to our target circle
And transform the ArrowHead shape...
g2d.setColor(Color.MAGENTA);
ArrowHead arrowHead = new ArrowHead();
AffineTransform at = AffineTransform.getTranslateInstance(
pointTo.getX() - (arrowHead.getBounds2D().getWidth() / 2d),
pointTo.getY());
at.rotate(from, arrowHead.getBounds2D().getCenterX(), 0);
arrowHead.transform(at);
g2d.draw(arrowHead);
Now, because I'm crazy, I also tested the code by drawing an arrow pointing at our source circle, just to prove that the calculations would work...
// This just proofs that the previous calculations weren't a fluke
// and that the arrow can be painted pointing to the source object as well
g2d.setColor(Color.GREEN);
arrowHead = new ArrowHead();
at = AffineTransform.getTranslateInstance(
pointFrom.getX() - (arrowHead.getBounds2D().getWidth() / 2d),
pointFrom.getY());
at.rotate(to, arrowHead.getBounds2D().getCenterX(), 0);
arrowHead.transform(at);
g2d.draw(arrowHead);
Let the first circle center coordinates are AX, AY, radius AR, and BX, BY, BR for the second circle.
Difference vector
D = (DX, DY) = (BX - AX, BY - AY)
Normalized
d = (dx, dy) = (DX / Length(D), DY / Length(D))
Start point of arrow
S = (sx, sy) = (AX + dx * AR, AY + dy * AR)
End point
E = (ex, ey) = (BX - dx * BR, BY - dy * BR)
Example:
AX = 0 AY = 0 AR = 1
BX = 4 BY = 3 BR = 2
D = (4, 3)
Length(D) = 5
dx = 4/5
dy = 3/5
sx = 0.8 sy = 0.6
ex = 4 - 2 * 4/5 = 12/5 = 2.4
ey = 3 - 2 * 3/5 = 9/5 = 1.8
Looking at the Screenshot, I think you need to find the top right corner of circle A, and then add half of the total distance to the bottom to y. Next, find the top right corner of circle B, and add half of the distance to the top left corner to x. Finally, make a line connecting the two, and render an arrow on the end of it.
Like this:
private int x1, y1, x2, y2 width = 20, height = 20;
private void example(Graphics g) {
// Set x1, x2, y1, and y2 to something
g.drawOval(x1, y1, width, height);
g.drawOval(x2, y2, width, height);
g.drawLine(x1, y1 + (height/2), x2 + (width/2), y2);
g.drawImage(/*Image of an arrow*/, (x2 + width/2)-2, y2);
}
My trick:
Let the two centers be C0 and C1. Using complex numbers, you map these two points to a horizontal segment from the origin by the transformation
P' = (P - C0) (C1 - C0)* / L
where * denotes conjugation and L = |C1 - C0|. (If you don't like the complex number notation, you can express this with matrices as well.)
Now the visible part of the segment goes from (R0, 0) to (L - R1, 0). The two other vertices of the arrow are at (L - R1 - H, W) and (L - R1 - H, -W) for an arrowhead of height H and width 2W.
By applying the inverse transform you get the original coordinates,
P = C0 + L P' / (C1 - C0)*.

Flipping a polygon that contains many polygons to create an upside down mirror of everything

I have created a polygon with 6 vertices. Lets call this one, outside polygon. Inside the outside polygon I created smaller polygons. I want to flip all of it vertically one point at the time.
I know the vertices of the outside polygon and I have an ArrayList<Polygon> for the inner polygons. I was able to flip the outside polygon. but how do I flipped the inner polygons keeping their relative positions in the new one? I know the center of the outside polygon and the flipped version.
correction: I needed to flip horizontal.
I flipped the outer polygon (triangle shape), and I was able to move the inner polygons. but the distance is incorrect. this is a picture of what I have done,
(https://docs.google.com/drawings/d/1cPYJqxTWVu5gSHFQyHxHWSTysNzxJvNuJIwsgCQInfc/edit) https://docs.google.com/drawings/d/1cPYJqxTWVu5gSHFQyHxHWSTysNzxJvNuJIwsgCQInfc/edit
I tried this:
for (Polygon p : polygonList) {
Polygon tempP = new Polygon(p.xpoints, p.ypoints, p.npoints);
firstPointinPolygon = new Point(p.xpoints[0], p.ypoints[0]);
// find frist point in the polygon
float adjacent = (float) firstPointinPolygon.getX() - 400;
float opposite = (float) firstPointinPolygon.getY() - 400;
float hypotenuse = (float) Math.sqrt(opposite * opposite + adjacent * adjacent);
float cosine = adjacent / hypotenuse;
float sine = opposite / hypotenuse;
float endX = 400 * cosine;
float endY = 400 * sine;
float endXDelta =400-endX;
float endYDelta=400-endY;
Polygon pM = move(tempP, endX, endY);
polygonListMirror.add(pM);
tempP = new Polygon();
}
public Polygon move(Polygon p, double xMove, double yMove) {
// Change the values of the points for the Polygon
for (int i = 0; i < p.xpoints.length; i++) {
p.xpoints[i] += xMove;
p.ypoints[i] += yMove;
}
return p;
}
But did not get the result, I expected. What am I doing wrong? The end result should be like the picture in this link:
(https://docs.google.com/drawings/d/1vYdWkCelWW1_NUypNhtmckBYfEMzCf6bMVtoB-AyPkw/edit) https://docs.google.com/drawings/d/1vYdWkCelWW1_NUypNhtmckBYfEMzCf6bMVtoB-AyPkw/edit
I think something like this will do it:
Polygon outerPolygon, oldOuterPolygon;
ArrayList<Polygon> innerPolygons;
// set up objects
for (Polygon polygon: innerPolygons)
{
for (int i = 0; i < polygon.ypoints.length; i++)
{
polygon.ypoints[i] = center(outerPolygon) - polygon.ypoints[i] + center(oldOuterPolygon);
}
}
If you just to flip it vertically where it stands, such that the y-coordinate of top-most and bottom-most points just switch around, center for both should be the same (thus you can just say 2*center).
I'm pretty sure you can replace center(outerPolygon) and center(oldOuterPolygon) with any point from the applicable Polygon, as long as both use the same point.

Put points round into circular arc used in java

I have me math question: I have known a circle center and radius, and have some uncertain number of points called N, my question is how to put the points on the circular arc, I cannot like put the points around the whole circumference, other as this link: http://i.6.cn/cvbnm/2c/93/b8/05543abdd33b198146d473a43e1049e6.png
in this link, you can read point is circle center, other color is some points, you can see these points around the arc.
Edit - in short: I have known a circle center and radius, so I want to generate some point around the circle center
I am not sure, but I checked this with simple Swing JComponent and seems ok.
Point center = new Point(100, 100); // circle center
int n = 5; // N
int r = 20; // radius
for (int i = 0; i < n; i++)
{
double fi = 2*Math.PI*i/n;
double x = r*Math.sin(fi + Math.PI) + center.getX();
double y = r*Math.cos(fi + Math.PI) + center.getY();
//g2.draw(new Line2D.Double(x, y, x, y));
}
It's not entirely clear what you're trying to accomplish here. The general idea of most of it is fairly simple though. There are 2*Pi radians in a circle, so once you've decided what part of a circle you want to arrange your points over, you multiply that percentage by 2*pi, and divide that result by the number of points to get the angle (in radians) between the points.
To get from angular distances to positions, you take the cosine and sine of the angle, and multiply each by the radius of the circle to get the x and y coordinate of the point relative to the center of the circle. For this purpose, an angle of 0 radians goes directly to the right from the center, and angles progress counter-clockwise from there.

Java 1.5 Issue with drawing shape using lines and angles

Hey, I'm trying to write a method that takes a starting Cartesian coordinate(x,y) an angle (in degrees), a length and a number of sides and draws a shape to an applet. So far this is what I have but, I cant figure out what I'm doing wrong. I plan on using line transformations for the actual angle change and that's not written in yet but the logic for drawing a line at an angle should work but isn't as far as I can tell. Could I get a couple of new eyes to look at this and tell me if I'm missing something.
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
Point startPt = new Point(0,0);
//Function in question
drawRegularPolygon(g, startPt, 5,60,50);
}
public static void drawRegularPolygon(Graphics g, Point2D startPoint, int numOfSides, int angle, int length)
{
Point2D current = startPoint;
for(int i=0; i<numOfSides; i++)
{
drawAngularLine(g, current, angle, length);
current = getEndPoint(current ,length,angle);
}
}
public static void drawAngularLine(Graphics g, Point2D startPoint, int angle, int length)
{
g.setColor(Color.BLACK);
Point2D endPoint = getEndPoint(startPoint, length, angle);
((Graphics2D) g).draw(new Line2D.Double(startPoint, endPoint));
}
private static Point2D getEndPoint(Point2D p, int length, int angle)
{
//Starting point you know (x1, x2),
//end point is (x1 + l * cos(ang), y1 + l * sin(ang))
//where l is the length and ang is the angle.
Point2D retVal = p;
double x = Math.cos(Math.toRadians(angle)*length+p.getX());
double y = Math.sin(Math.toRadians(angle)*length+p.getY());
retVal.setLocation(x,y);
return retVal;
}
A couple things. The first is to be careful about what you're taking sin/cosine of. It's not cos(angle*length) but rather length*cos(angle).
The second point is to think about coordinate systems. It might help to do the math assuming the initial point is (0,0), and then translate to the screen coordinates. This helps avoid the confusion of the y-axis seeming to be upside-down (values increase from top to bottom).
So assuming we just want a point that's length,angle away from the origin in a standard right-handed system, we'd get:
x1 = length * cos(angle)
y1 = length * sin(angle)
But since negative-y is up, we actually want
x2 = length * cos(angle)
y2 = -length * sin(angle)
To mentally check this, picture that you're doing this math at the origin (0,0) which is in the upper left, and have an angle of 45°. If y2 were positive, we'd end up seeing an angle that looks to us like -45°.
Now translate the origin to our starting point (x_i, y_i), to get our final values:
x_f = x_i + length * cos(angle)
y_f = y_i + (-length * cos(angle)) = y_i - length * cos(angle)
Alternatively, if it makes more sense to work in a standard right-handed coordinate system, you probably could get away with doing all the math as if (0,0) were in the center, and then applying a translation and a y-axis mirror transformation, but this screen coordinate system isn't too difficult to work within once you get used to flipping the y values around.
You are drawing a line with the same start point and end point - so nothing is drawn.
Java objects are passed by reference, so:
private static Point2D getEndPoint(Point2D p, int length, int angle){
Point2D retVal = p;
retVal.setLocation(x,y);
return retVal;
}
is also changing the starting point p. So it draws a line of length 1 (does it show a dot on the screen?).
Try using:
Point2D retVal = p.clone();

Categories

Resources