a82382fb65e2cbcd8ab7f1e25fba0847f6d6fdec
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / geometry / Point2D.java
1 /*
2  * Sixth 3D engine. Author: Svjatoslav Agejenko. 
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.sixth.e3d.geometry;
6
7 import static java.lang.Math.sqrt;
8
9 public class Point2D implements Cloneable {
10
11     public double x, y;
12
13     public Point2D() {
14     }
15
16     public Point2D(final double x, final double y) {
17         this.x = x;
18         this.y = y;
19     }
20
21     public Point2D(final Point2D parent) {
22         x = parent.x;
23         y = parent.y;
24     }
25
26     /**
27      * Add other point to current point.
28      *
29      * @return current point.
30      */
31     public Point2D add(final Point2D otherPoint) {
32         x += otherPoint.x;
33         y += otherPoint.y;
34         return this;
35     }
36
37     public boolean isZero() {
38         return (x == 0) && (y == 0);
39     }
40
41     @Override
42     public Point2D clone() {
43         return new Point2D(this);
44     }
45
46     public void clone(final Point2D parent) {
47         x = parent.x;
48         y = parent.y;
49     }
50
51     public Point2D getMiddle(final Point2D p1, final Point2D p2) {
52         x = (p1.x + p2.x) / 2d;
53         y = (p1.y + p2.y) / 2d;
54         return this;
55     }
56
57     public double getAngleXY(final Point2D anotherPoint) {
58         return Math.atan2(x - anotherPoint.x, y - anotherPoint.y);
59     }
60
61     /**
62      * Compute distance to another point.
63      */
64     public double getDistanceTo(final Point2D anotherPoint) {
65         final double xDiff = x - anotherPoint.x;
66         final double yDiff = y - anotherPoint.y;
67
68         return sqrt(((xDiff * xDiff) + (yDiff * yDiff)));
69     }
70
71     public double getVectorLength() {
72         return sqrt(((x * x) + (y * y)));
73     }
74
75     public Point2D invert() {
76         x = -x;
77         y = -y;
78         return this;
79     }
80
81     public void roundToInteger() {
82         x = (int) x;
83         y = (int) y;
84     }
85
86     /**
87      * Subtract other point from current point.
88      *
89      * @return current point.
90      */
91     public Point2D subtract(final Point2D otherPoint) {
92         x -= otherPoint.x;
93         y -= otherPoint.y;
94         return this;
95     }
96
97     public Point3D to3D() {
98         return new Point3D(x, y, 0);
99     }
100
101     public Point2D zero() {
102         x = 0;
103         y = 0;
104         return this;
105     }
106
107     @Override
108     public String toString() {
109         return "Point2D{" +
110                 "x=" + x +
111                 ", y=" + y +
112                 '}';
113     }
114 }