I recently started learning Java and I'm having some trouble understanding how to make arrays to work the way I want them to.
Here I have an assignment of creating a polygon class with different methods inside.
Basically the class represents a convex polygon in a plane.
The array receives user input that consists of x and y coordinates and places them inside. (max number of vertices is 10).
There are some functions that I have no idea how to do and I would really appreciate some help with.
Point Class - which is used to get coordinates
public class Point {
private double _x;
private double _y;
public Point() {
this._x = 0.0D;
this._y = 0.0D;
}
public Point(double x, double y) {
this._x = x;
this._y = y;
}
public Point(Point other) {
this._x = other._x;
this._y = other._y;
}
public double getX() {
return this._x;
}
public double getY() {
return this._y;
}
public void setX(double x) {
if (x >= 0.0D)
this._x = x;
}
public void setY(double y) {
if (y >= 0.0D)
this._y = y;
}
public boolean isAbove(Point other) {
return (this._y > other._y);
}
public boolean isUnder(Point other) {
return other.isAbove(this);
}
public boolean isLeft(Point other) {
return (this._x < other._x);
}
public boolean isRight(Point other) {
return other.isLeft(this);
}
public double distance(Point other) {
double distance = Math.sqrt(Math.pow(this._x - other._x, 2.0D) + Math.pow(this._y - other._y, 2.0D));
return distance;
}
public void move(double dx, double dy) {
double x = this._x + dx;
double y = this._y + dy;
if (x >= 0.0D && y >= 0.0D) {
this._x = x;
this._y = y;
}
}
public boolean equals(Point other) {
return (this._x == other._x && this._y == other._y);
}
public String toString() {
return "(" + this._x + "," + this._y + ")";
}
}
Polygon Class - main class im working on
/**
* Write a description of class Polygon here.
*
* #author [REDACTED]
* #version (Ver 1.0)
*/
public class Polygon {
private Point[] _vertices;
private int _noOfVertices;
public Polygon() {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
}
public Polygon(Point[] arr) {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
if (arr.length > 10) {
return;
}
// for (Point P : arr)
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
_vertices[i] = arr[i];
_noOfVertices++;
}
}
}
public boolean addVertex(double x, double y) {
if (_noOfVertices >= 10)
return false;
Point p = new Point(x, y);
_vertices[_noOfVertices] = p;
_noOfVertices++;
return true;
}
public Point highestVertex() {
for (int i = 0; i < _noOfVertices; i++) {
}
}
public String toString() {
}
public double calcPerimeter() {
for (int i = 0; i < arr.length; i++) {
}
}
public double caclArea() {
Point ppp = _vertices[zzz]
}
public boolean isBigger(Polygon other) {
}
public int findVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
return i;
}
}
return -1;
}
public Point getNextVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
if (i == _noOfVertices - 1) {
return new Point(_vertices[0]);
}
return new Point(_vertices[i + 1]);
}
}
return null;
}
public Polygon getBoundingBox() {
}
}
I have no idea how to do these functions:
Line 44: public Point highestVertex() {} - returns a copy of the highest point in the polygon. If there is more than one vertice at the same Y - the method will return the first one it encountered (with the said Y) If there are no vertices aka the array is empty it will return null.
Line 52: public String toString() {} - method that returns a string of points representing the polygon. The string should be in the following format:
The polygon has 5 vertices:
((2.0,1.0),(5.0,0.0),(7.0,5.0),(4.0,6.0),(1.0,4,0))
If there are no vertices the method will return a string in the following format:
The polygon has 0 vertices.
English is not my first language so I apologize for any grammar mistakes in advance.
First, it's not really the best to ask homework questions here, this is a concept that you should learn.
In highestVertex(), they outline the 3 cases for you:
1st case: If point-y is equal to another point-y, return the first vertex that has point-y.
2nd case: if arr has no elements return null.
3rd case: in loop, check each element's y value in the array and compare it to the biggest y so far.
Use this line before your loop:
int max = Integer.MIN_VALUE;
Inside loop:
if (arr[i] > max) max = arr[i]
For toString(), again loop throughout the array, and add each point to a tracker string that you will return.
String str = "";
loop
str += arr[i].toString() + ",";
This works except you need to loop until arr's second to last element, as you will have an extraneous comma after the last point.
Related
I am trying to create a 2D game engine in Java with LWJGL 3. For now the objects are only rectangles with box colliders. For the collision detection I change the edge of the rectangles in to lines with the y = ax + b structure. One of the rectangles has a rigidbody component, that gives it the ability to move and interact with environment. The idea for now is to give the rigidbody a force at the start, gravity turned off, no friction, and a perfect bounce (bounciness=1). It all works very well, till it hits a rectangle with no vertical and horizontal edges. I found out that if the non-rigidbody objects are rotated by an angle other than 90 or 180 degrees the normal force is wrong (too small), how wrong depends on the rotation. The rotation of the rigidbody doesn't contribute to the problem.
Vector2 rotSurface = new Vector2(-collision.surface.ToVector().y, collision.surface.ToVector().x).getNormalized();
System.out.println("Angle: "+Physics.Angle(rotSurface, rb.force));
Vector2 normalForce = rotSurface.multiplyBy(rotSurface.multiplyBy(rb.force).getMagnitude());
rb.force = rb.force.add(normalForce).multiplyBy(1f - rb.friction).add(normalForce.multiplyBy(rb.bounciness));
System.out.println("Angle: "+Physics.Angle(rotSurface, rb.force));
System.out.println("===");
Am I doing something wrong here with calculating the new rigidbody force or the normal force itself? If you need more information to help me solve this problem please ask.
Classes that I use in the code above:
public class Collision {
Collider collider;
ArrayList<Vector2> contactPoints = new ArrayList<Vector2>();
Vector2 center = Vector2.zero;
Line surface;
public Collision(Collider collider, ArrayList<Vector2> contactPoints, Line surface) {
this.collider = collider;
this.contactPoints = contactPoints;
for(int i = 0; i < contactPoints.size(); i++) {
center = contactPoints.get(i).add(center).divideBy(2);
}
this.surface = surface;
}
}
class Line {
Vector2 begin, eind;
public float rc = 0;
public float b = 0;
public float x, y;
public boolean vertical = false;
public boolean horizontal = false;
public Line(Vector2 begin, Vector2 eind) {
this.begin = begin;
this.eind = eind;
if(begin.y == eind.y) {
this.y = begin.y;
this.horizontal = true;
}
else if(begin.x == eind.x){
this.x = begin.x;
this.vertical = true;
} else {
this.rc = (eind.y - begin.y) / (eind.x - begin.x);
this.b = GetB(rc, begin);
}
}
public float GetB(float rc, Vector2 punt) {
return punt.y - (rc * punt.x);
}
public Vector2 GetIntersection(Line l2) {
float x_ = rc - l2.rc;
if(vertical) {
x_ = x;
if(l2.horizontal) {
return new Vector2(x, l2.y);
}
else if(!l2.vertical){
//System.out.println("gert");
return new Vector2(x, l2.rc * x + l2.b);
}
} else if(horizontal) {
if(l2.vertical) {
return new Vector2(l2.x, y);
} else if(!l2.horizontal) {
return new Vector2((y-l2.b) / l2.rc, y);
}
} else {
if(l2.vertical) {
return new Vector2(l2.x, rc * l2.x + b);
} else if(l2.horizontal) {
return new Vector2((l2.y - b) / rc, l2.y);
}
}
if(x_ == 0) {
return null;
}
float getal = l2.b - b;
x_ = getal / x_;
float y_ = rc * x_ + b;
return new Vector2(x_, y_);
}
public Vector2 ToVector() {
return eind.substract(begin);
}
public float GetDisTo(Vector2 point) {
Vector2 point1 = begin.add(eind).divideBy(2);
return (float) Math.sqrt(Math.pow(point1.x - point.x, 2) + Math.pow(point1.y - point.y, 2));
}
public boolean Overlaps(Line line) {
if(horizontal && y == line.y) {
if(((line.begin.x > begin.x && line.begin.x < eind.x) || (line.eind.x > begin.x && line.eind.x < eind.x)) ||
((begin.x > line.begin.x && begin.x < line.eind.x) || (line.eind.x > line.begin.x && eind.x < line.eind.x)))
return true;
} else if(vertical && x == line.x) {
//return true;
}
return false;
}
}
class Vector2 {
float x, y;
public static Vector2 zero = new Vector2(0, 0);
public Vector2(float x, float y) {
this.x = x;
this.y = y;
}
public Vector2 multiplyBy(Vector2 vector) {
return new Vector2(x * vector.x, y * vector.y);
}
public Vector2 multiplyBy(float getal) {
return new Vector2(x * getal, y * getal);
}
public Vector2 divideBy(Vector2 vector) {
return new Vector2(x / vector.x, y / vector.y);
}
public Vector2 divideBy(float getal) {
return new Vector2(x / getal, y / getal);
}
public Vector2 add(Vector2 vector) {
return new Vector2(x + vector.x, y + vector.y);
}
public Vector2 substract(Vector2 vector) {
return new Vector2(x - vector.x, y - vector.y);
}
public float getMagnitude() {
return (float)Math.sqrt(x*x + y*y);
}
public Vector2 getNormalized() {
return divideBy(getMagnitude());
}
}
Fixed it by using a sinus.
I replaced
Vector2 normalForce = rotSurface.multiplyBy(rotSurface.multiplyBy(rb.force).getMagnitude());
with
Vector2 normalForce = rotSurface.multiplyBy((float)Math.sin(Math.toRadians((double) (90f - Physics.Angle(rotSurface, force)))) * force.getMagnitude());
I am trying to make a grid (with minimal code) that blocks can snap to. What I want is when the mouse is in the grid square, the block moves to that square. What I have written essentially says that if the X or Y are beyond the grid block times the size of the block, move to the next grid block. Currently, this code creates a 3x3 grid, though the code SHOULD generate infinite gridspaces. I cannot move the block outside of this 3x3 grid.
public class Player extends Entity {
public Player(double entSize, boolean collideA, boolean collideB, double x, double y) {
super(entSize, collideA, collideB, x, y);
}
public void init() {
Texture texFile = loadTexture("stone");
texture(false, true);
texFile.bind();
render();
}
void input() {
int gridPosX = 1;
int gridPosY = 1;
if(getX() > gridPosX*entSize) {
gridPosX += 1;
} if(getX() < gridPosX*entSize) {
gridPosX -= 1;
} if(getY() > gridPosY*entSize) {
gridPosY += 1;
} if(getY() < gridPosY*entSize) {
gridPosY -= 1;
}
this.x = gridPosX*entSize;
this.y = gridPosY*entSize;
}
}
The X and Y values are what define the blocks position and shape parameters.
Fixed by using for loops for the positive grid increments!
NEW CODE:
public class Player extends Entity {
public Player(double entSize, boolean collideA, boolean collideB, double x, double y) {
super(entSize, collideA, collideB, x, y);
}
public void init() {
Texture texFile = loadTexture("stone");
texture(false, true);
texFile.bind();
render();
}
void input() {
int gridPosX = 0;
int gridPosY = 0;
for(gridPosX = 0; getX() > gridPosX*entSize; gridPosX++) {
gridPosX += 0;
} if(getX() < gridPosX*entSize) {
gridPosX -= 1;
} for(gridPosY = 0; getY() > gridPosY*entSize; gridPosY++) {
gridPosY += 0;
} if(getY() < gridPosY*entSize) {
gridPosY -= 1;
}
this.x = gridPosX*entSize;
this.y = gridPosY*entSize;
}
}
I am getting a null pointer exception when I try to use the perimeter function in my code. It seems that the Points array (Point is a simple object with an x and y coordinate) is not correctly initialising, I believe I may have declared the array wrongly or the constructor is incorrect.
package shapes;
import static java.lang.Math.*;
public class Triangle {
private int sides = 3;
private Point[] Points = new Point[sides];
public Triangle(Point[] vertices) {
vertices = Points;
}
public double perimeter() {
return Points[0].distance(Points[1]) + Points[1].distance(Points[2]) + Points[2].distance(Points[0]);
}
public double area() {
double semiperimeter = perimeter() / 2;
return sqrt(semiperimeter * (semiperimeter - Points[0].distance(Points[1])) * (semiperimeter - Points[1].distance(Points[2])) * (semiperimeter - Points[2].distance(Points[0])));
}
#Override
public String toString() {
return "Triangle has perimeter of " + perimeter() + " and an area of " + area();
}
public void translate(int dx, int dy) {
for(int i = 0; i < 3; i++) {
Points[i].translate(dx, dy);
}
}
public void scale(int factor) {
for(int i = 0; i < 3; i++) {
Points[i].scale(factor);
}
}
public Point getVertex(int i) {
return Points[i];
}
}
Any help is much appreciated!
You need to reverse this in your constructor:
vertices = Points;
to
Points = vertices ;
You need to initialize your Points array with the input vertices and not the other way around.
Suppose one has a simple class:
public class Point implements Comparable<Point> {
public int compareTo(Point p) {
if ((p.x == this.x) && (p.y == this.y)) {
return 0;
} else if (((p.x == this.x) && (p.y > this.y)) || p.x > this.x) {
return 1;
} else {
return -1;
}
}
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
And a HashMap from Point to something, let's say Cell:
cellMap = new HashMap<Point, Cell>();
Then one fills in cellMap as follows:
for (int x = -width; x <= width; x++) {
for (int y = -height; y <= height; y++) {
final Point pt = new Point(x,y);
cellMap.put(pt, new Cell());
}
}
}
And then one does something like (trivial) this:
for (Point pt : cellMap.keySet()) {
System.out.println(cellMap.containsKey(pt));
Point p = new Point(pt.getX(), pt.getY());
System.out.println(cellMap.containsKey(p));
}
And gets true and false in, respectively, first and second cases. What is going on? Is this map comparing hashes instead of values? How to make the example return true in both cases?
Since you are using HashMap, not TreeMap, you need to override hashCode and equals, not compareTo, in your Point class:
#Override
public int hashCode() {
return 31*x + y;
}
#Override
public bool equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Point)) return false;
Point p = (Point)other;
return x == p.x && y == p.y;
}
So for this project I wish to input an array containing a number of points. (no specific number). I am confused on how I should approach the methods and constructor because some of the methods call for changes such as grabbing the average of the X or Y values. Am I approaching this project in the right way? Should I be using a clone of the point list, or an array list or what... (note I am only showing part of the PolygonImpl class as an example, they all function similarly) The class point contains :
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public Point translate(double dx, double dy) {
return new Point(x+dx, y+dy);
}
public double distanceTo(Point p) {
return Math.sqrt((p.x - x)*(p.x -x) + (p.y-y)*(p.y-y));
}
}
public class PolygonImpl implements Polygon {
private double xSum=0;
private double ySum=0;
private ArrayList<Point> points;
private Point[] pList;
private Point a;
PolygonImpl(Point[] pList) {
this.pList = pList.clone();
points = new ArrayList<Point>();
for (int index = 0; index < pList.length; index++) {
points.add(pList[index]);
xSum += pList[index].getX();
ySum += pList[index].getY();
}
}
public Point getVertexAverage() {
double xSum = 0;
ArrayList<Point> vlist = new ArrayList<Point> ();
double ySum = 0;
for (int index = 0; index < vlist.size(); index++) {
xSum = xSum + vlist.get(index).getX();
ySum = ySum + vlist.get(index).getY();
}
return new Point(xSum/getNumSides(), ySum/getNumSides());
}
public int getNumSides() {
return pList.length;
}
public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());
}
public void scale(double factor) {
ArrayList<Point> points = new ArrayList<Point> ();
for (int index = 0; index < pList.length; index++) {
{ double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
points.add(index,a);
}
}
}
In this case, I don't think you need the extra List objects; they are redundant.
Here is the code just using the pList array.
public class PolygonImpl implements Polygon {
private double xSum=0;
private double ySum=0;
private Point[] pList;
private Point a;
PolygonImpl(Point[] pList) {
this.pList = pList.clone();
for (int index = 0; index < pList.length; index++) {
xSum += pList[index].getX();
ySum += pList[index].getY();
}
}
public Point getVertexAverage() {
double xSum = 0;
double ySum = 0;
for (int index = 0; index < pList.length; index++) {
xSum = xSum + pList[index].getX();
ySum = ySum + pList[index].getY();
}
return new Point(xSum/getNumSides(), ySum/getNumSides());
}
public int getNumSides() {
return pList.length;
}
public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());
}
public void scale(double factor) {
for (int index = 0; index < pList.length; index++)
{
double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
pList[index] = a;
}
}
There are at least three things here that need pointing out.
The first is the difference between "clone" and "copy." .clone is a shallow copy; that means if you change the clone, you also change the original.
The second is regarding your use of collections. Since a polygon is a collection of points, either an array or an ArrayList would be approriate, but there is no point in using bother, or, if there is, think long and hard about whether it's a good point, and then explain in the inline documentation why it matters, else it will come back to bite you in the form of using one when you mean the other.
Third is scope. Your polygon class has instance variables (xSum and ySum) that are occluded by variables with the same name in getVertexAverage. The way they are used in getVertexAverage is appropriate in itself; the instance variables are only useful if you mean to cache the sums, which becomes more questionable, because every operation that changes a point invalidates the instance values.
Instance values are for storing data about an object (in this case, points are reasonable); instance methods are for operating on that data at a given state (in this case, the average).
Keeping this in mind, you can now understand how the move method isn't finished :)