java class- setX circle method - java

I am having problems with my homework assignment. I created a Circle class but i'm getting some errors while using the setX and setY methods. that i don't know how to fix. My code is below. Thank you.
import java.awt.Point;
public class Circle {
private Point origin;
private double radius;
public Circle(Point o, double r)
{
setOrigin(o);
setRadius(r);
}
public Circle(double xValue, double yValue, double r)
{
origin.setX(xValue);
origin.setY(yValue);
setRadius(r);
}
public Circle()
{
setX(0.0);
setY(0.0);
setRadius(1);
}
public Circle(Circle c)
{
setOrigin(c.getOrigin());
setRadius(c.getRadius());
}
Point getOrigin()
{
return new Point(origin);
}
public void setOrigin(Point p)
{
origin.setX(p.getX());
origin.setY(p.getY());
}
public void setX(double value)
{
origin.setX(value);
}
public double getX()
{
return origin.getX();
}
public void setY(double value)
{
origin.setY(value);
}
public double getY()
{
return origin.getY();
}
public void setRadius(double value)
{
radius = value;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return (radius * radius) * Math.PI;
}
public String toString()
{
return "(" + origin.getX() + ", " + origin.getY() + ", " + radius + ")";
}
public boolean equals(Circle c)
{
if (origin.getX() == c.getX() && origin.getY() == c.getY() &&
getRadius() == c.getRadius())
{
return true;
}
else
{
return false;
}
}
public boolean doesOverlap(Circle oC)
{
double distance = Math.sqrt((Math.pow(getX() - oC.getX(), 2) + Math.pow(getY()-oC.getY(), 2)));
if ((radius + oC.radius) > distance)
{
return true;
}
else
{
return false;
}
}
}
public class Point {
private double x;
private double y;
public Point(double xValue, double yValue)
{
x = xValue;
y = yValue;
}
public Point(Point p) {
this(p.x, p.y);
}
public Point() {
this(0, 0);
}
public void setX(double xValue)
{
x = xValue;
}
public double getX()
{
return x;
}
public void setY(double xValue)
{
y = xValue;
}
public double getY()
{
return y;
}
public boolean equals(Point otherPoint)
{
return (this.x == otherPoint.x) && (this.y == otherPoint.y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}

Have a look at the API of Point. There are no such methods like setX(...)
Additionally, I think you should initialize it especially in your second and third constructor
public Circle(double xValue, double yValue, double r){...}
public Circle(){...}
via
origin = new Point();

Related

Calculating the distance between a line segment and a point

I am currently developing a tower defense game in java from scratch and I am reworking the bullet collisions. for this I need to calculate the distance between a given point and a line segment. I have already written a function to do just that, but it does often give the distance from one of the points when it is not supposed to.
the line segment class:
public class LineSegment {
public Vector2DK p;
public Vector2DK q;
/**
* Creates a line segment between the points P and Q
* #param p Point P
* #param q Point Q
*/
public LineSegment(Vector2DK p, Vector2DK q) {
this.p = p;
this.q = q;
}
/**
* Calculates the distance to point R
* #param r Point R
* #return Distance
*/
public double distanceFrom(Vector2DK r) {
// after trying what feels like everything I might have gotten a little confused(stupid errors ahead)
Vector2DP differenceVector = r.subtract(p).toPolar();
Vector2DP differenceVector2 = r.subtract(q).toPolar();
double alpha = differenceVector.getAngle() - q.subtract(p).getAngle();
double beta = differenceVector2.getAngle() - q.subtract(p).getAngle();
if (alpha < Math.PI / 2 && alpha > -Math.PI / 2) {
return p.distanceTo(r);
} else if (beta > Math.PI / 2 || beta < -Math.PI / 2) {
return q.distanceTo(r);
}
return Math.abs(differenceVector.getMagnitude() * Math.sin(alpha));
}
public static void main(String[] args) {
// a main method for testing
// I already added a case where the bullet of the tower flew right thru the enemy(but I probably got the wrong tick, so the values are probably not good for testing)
Vector2DK linePoint0 = new Vector2DK(339.9354152826523, 374.7835775987438);
Vector2DK linePoint1 = new Vector2DK(317.79869321314067, 388.4287303893724);
Vector2DK point = new Vector2DK(290.0194200000002, 400.0);
LineSegment lineSegment = new LineSegment(linePoint0, linePoint1);
Line line = new Line(linePoint0, linePoint1);
System.out.println(lineSegment.distanceFrom(point));
}
}
my two vector classes:
public class Vector2DK implements Vector2D {
private double x;
private double y;
public Vector2DK(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2DK(Vector2D vector) {
Vector2DK vector2DK = vector.toKartesian();
x = vector2DK.x;
y = vector2DK.y;
}
public void copyToSelf(Vector2DK vector) {
x = vector.x;
y = vector.y;
}
#Override
public String toString() {
return String.format("Vector2DK(%s, %s)", x, y);
}
#Override
public Vector2DK toKartesian() {
return new Vector2DK(x, y);
}
#Override
public Vector2DP toPolar() {
return new Vector2DP(getMagnitude(), getAngle());
}
#Override
public double getAngle() {
return Math.atan2(y, x);
}
#Override
public double getMagnitude() {
return Math.sqrt(getMagnitudeSquare());
}
#Override
public double getX() {
return x;
}
#Override
public double getY() {
return y;
}
#Override
public void setAngle(double angle) {
Vector2DP vector = toPolar();
vector.setAngle(angle);
copyToSelf(vector.toKartesian());
}
#Override
public void setMagnitude(double magnitude) {
Vector2DP vector = toPolar();
vector.setAngle(magnitude);
copyToSelf(vector.toKartesian());
}
#Override
public void setX(double x) {
this.x = x;
}
#Override
public void setY(double y) {
this.y = y;
}
#Override
public double getMagnitudeSquare() {
return x * x + y * y;
}
#Override
public double distanceTo(Vector2D vector) {
return Math.sqrt(MathFunc.square(x - vector.getX()) + MathFunc.square(y - vector.getY()));
}
#Override
public void normalize() {
double magnitude = getMagnitude();
x /= magnitude;
y /= magnitude;
}
#Override
public void reverse() {
x = -x;
y = -y;
}
#Override
public Vector2D add(Vector2D vector) {
return new Vector2DK(x + vector.getX(), y + vector.getY());
}
#Override
public Vector2D subtract(Vector2D vector) {
return new Vector2DK(x - vector.getX(), y - vector.getY());
}
#Override
public Vector2D scale(double value) {
return new Vector2DK(x * value, y * value);
}
#Override
public void addWith(Vector2D vector) {
x += vector.getX();
y += vector.getY();
}
#Override
public void subtractWith(Vector2D vector) {
x -= vector.getX();
y -= vector.getY();
}
#Override
public void scaleWith(double value) {
x *= value;
y *= value;
}
#Override
public double dotProduct(Vector2D vector) {
return x * vector.getX() + y * vector.getY();
}
}
and:
public class Vector2DP implements Vector2D {
private double magnitude;
private double angle;
public Vector2DP(double magnitude, double angle) {
this.magnitude = magnitude;
this.angle = angle;
}
public Vector2DP(Vector2DP vector) {
Vector2DP vector2DP = vector.toPolar();
this.magnitude = vector.magnitude;
this.angle = vector.angle;
}
public void copyToSelf(Vector2DP vector) {
magnitude = vector.magnitude;
angle = vector.angle;
}
#Override
public String toString() {
return String.format("Vector2DP(%su, %s°)", magnitude, Math.toDegrees(angle));
}
#Override
public Vector2DK toKartesian() {
return new Vector2DK(getX(), getY());
}
#Override
public Vector2DP toPolar() {
return new Vector2DP(magnitude, angle);
}
#Override
public double getAngle() {
return angle;
}
#Override
public double getMagnitude() {
return magnitude;
}
#Override
public double getX() {
return Math.cos(angle) * magnitude;
}
#Override
public double getY() {
return Math.sin(angle) * magnitude;
}
#Override
public void setAngle(double angle) {
this.angle = angle;
}
#Override
public void setMagnitude(double magnitude) {
this.magnitude = magnitude;
}
#Override
public void setX(double x) {
Vector2DK vector = toKartesian();
vector.setX(x);
copyToSelf(vector.toPolar());
}
#Override
public void setY(double y) {
Vector2DK vector = toKartesian();
vector.setY(y);
copyToSelf(vector.toPolar());
}
#Override
public double getMagnitudeSquare() {
return magnitude * magnitude;
}
#Override
public double distanceTo(Vector2D vector) {
return subtract(vector).getAngle();
}
#Override
public void normalize() {
magnitude = 1;
}
#Override
public void reverse() {
angle += angle < Math.PI ? Math.PI : -Math.PI;
}
#Override
public Vector2D add(Vector2D vector) {
return toKartesian().add(vector).toPolar();
}
#Override
public Vector2D subtract(Vector2D vector) {
return toKartesian().add(vector).toPolar();
}
#Override
public Vector2D scale(double value) {
return new Vector2DP(magnitude * value, angle);
}
#Override
public void addWith(Vector2D vector) {
copyToSelf((Vector2DP) add(vector));
}
#Override
public void subtractWith(Vector2D vector) {
copyToSelf((Vector2DP) subtract(vector));
}
#Override
public void scaleWith(double value) {
magnitude *= value;
}
#Override
public double dotProduct(Vector2D vector) {
Vector2DP vector2DP = vector.toPolar();
return magnitude * vector2DP.magnitude * Math.cos(angle - vector2DP.angle);
}
}
Consider the next Python code (hope it is easy to translate it).
At first function check dot products of segment vector and vectors from the start and end of segment to the point.
If projection of point onto the line lies outside the segment, sign of dot product reveals this fact, and we return distance to the closest segment end (points A,B,C,D at the picture)
Otherwise we return length of projection (formula from wiki) (point E at the picture)
hypot gives vector length (like your getMagnitude)
import math
def pt_seg_dist(px, py, qx, qy, rx, ry):
qpx = qx - px
qpy = qy - py
rpx = rx - px
rpy = ry - py
if rpx * qpx + rpy * qpy <= 0:
return math.hypot(rpx, rpy)
rqx = rx - qx
rqy = ry - qy
if rqx * qpx + rqy * qpy >= 0:
return math.hypot(rqx, rqy)
return abs(rpx * qpy - rpy * qpx) / math.hypot(qpx, qpy)
print(pt_seg_dist(0, 0, 1, 0, 0.5, 2))
print(pt_seg_dist(0, 0, 1, 0, -2, 2))
print(pt_seg_dist(0, 0, 1, 0, 3, -2))
>>>
2.0
2.8284271247461903
2.8284271247461903

Collision Detection Glitches

Thanks in advance. I am trying to make a scrolling 2d game with perfect collision detections on the corners of the player. The problem I am having is that if you go left or down on a wall, it works just fine, but on the right or up, it seems to infinitely detect collisions and glitch you to a corner.
I have tried resetting the motion, reverting to old location, subtracting pixels from the position after the translation, and also changing the variables.
package me.Rigidity.Apocalypse;
public class Entity extends Tile {
private float x, y, xm, ym;
public Entity(String name, float r, float g, float b, float x, float y, float size) {
super(name, r, g, b);
this.size = size;
this.x = x;
this.y = y;
}
public void move(float x, float y) {
this.x += x;
this.y += y;
}
public void position(float x, float y) {
this.x = x;
this.y = y;
}
public void factor(float x, float y) {
this.xm *= x;
this.ym *= y;
}
public void motion(Map map) {
motionX(map);
motionY(map);
}
public void motionX(Map map) {
x += xm;
if (collision(map)) {
if (left(map)) {
x = rightX();
}
if (right(map)) {
x = leftX();
}
}
}
public void motionY(Map map) {
y += ym;
if (collision(map)) {
if (top(map)) {
y = bottomY();
return;
}
if (bottom(map)) {
y = topY();
}
}
}
public void motion(float x, float y) {
xm += x;
ym += y;
}
public float x() {
return x;
}
public float y() {
return y;
}
public void x(float x) {
this.x = x;
}
public void y(float y) {
this.y = y;
}
public float xm() {
return xm;
}
public float ym() {
return ym;
}
public Tile bottomleft(Map map) {
return map.getAbsoluteTile(leftX(), bottomY());
}
public Tile bottomright(Map map) {
return map.getAbsoluteTile(rightX(), bottomY());
}
public Tile topleft(Map map) {
return map.getAbsoluteTile(leftX(), topY());
}
public Tile topright(Map map) {
return map.getAbsoluteTile(rightX(), topY());
}
public int leftX() {
return (int)(((int)(x/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size()-size);
}
public int rightX() {
return (int)(((int)(x/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size());
}
public int topY() {
return (int)(((int)(y/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size());
}
public int bottomY() {
return (int)(((int)(y/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size()-size);
}
public boolean top(Map map) {
return topleft(map) instanceof Solid || topright(map) instanceof Solid;
}
public boolean bottom(Map map) {
return bottomleft(map) instanceof Solid || bottomright(map) instanceof Solid;
}
public boolean left(Map map) {
return topleft(map) instanceof Solid || bottomleft(map) instanceof Solid;
}
public boolean right(Map map) {
return topright(map) instanceof Solid || bottomright(map) instanceof Solid;
}
public boolean collision(Map map) {
return bottomleft(map) instanceof Solid || topleft(map) instanceof Solid || bottomright(map) instanceof Solid || topright(map) instanceof Solid;
}
}
There is no error message, however the result isn't as expected on the right or top collision. Left and bottom work as expected with clean collision, as well as the sliding motion.

Clones method is not working

I seem to be getting an error at the catch CloneNotSupportedException.
public class Segment extends Point implements Cloneable {
private Point p1, p2;
public Segment() {
this.p1 = new Point();
this.p2 = new Point();
}
public Segment clone() {
try {
Segment cloned = (Segment) super.clone();
cloned.p1 = (Point) p1.clone();
cloned.p2 = (Point) p2.clone();
return (cloned);
} catch (CloneNotSupportedException cnse) { // This is the error
cnse.printStackTrace();
return null;
}
}
}
package myclasses;
public class Point implements Cloneable
{
private int x, y;
public Point()
{
x = 0;
y = 0;
}
public Point(int X, int Y)
{
this.x = X;
this.y = Y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void setX(int x)
{
this.x = x;
}
private void setY(int y)
{
this.y = y;
}
public void setPoint(int newX, int newY)
{
getX();
getY();
setX(x);
setY(y);
}
public void up(int i)
{
y = getY() + i;
}
public void down(int i)
{
y = getY() - i;
}
public void left(int i)
{
x = getX() - i;
}
public void right(int i)
{
x = getX() + i;
}
public String toString()
{
return "(" + getX() + "," + getY() + ")";
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point that = (Point) obj;
if (y != that.y)
return false;
if (x != that.x)
return false;
return true;
}
public Point clone()
{
try
{
return (Point) super.clone();
}
catch(CloneNotSupportedException cnse)
{
System.out.println(cnse);
return null;
}
}
}
Error reported by javac is
error: exception CloneNotSupportedException is never thrown in body of corresponding try statement
} catch (CloneNotSupportedException cnse) { // This is the error
You can declare Point.clone() like this
public Point clone() throws CloneNotSupportedException
Then javac won't complain. Or even simpler do not try to catch exception.

How to create an object from data in a file and assign it to an array?

I need to take information from a file and create them into objects and put them into an array so I can compare the areas of the objects and list in the array which object has the largest area and its location in the array.
I'm confused on how I take the information from the file and create each one into a object (circle or rectangle) and then assign that object into an array after it has been created. I think my other classes are fine, I'm just stuck on finishing the driver.
Normally, I would do something like Circle c1 = new Circle(); to create a new object, but how do I do that from a file with predefined information and assign it to an array?
Data:
“CIRCLE”, 1, “blue”, true
“RECTANGLE”, 1, 2, “blue”, true
“RECTANGLE”, 10, 2, “red”, true
“CIRCLE”, 2, “green”
“RECTANGLE”
“CIRCLE”
Driver:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("C:/Users/Charles/Desktop/GeometricObjectsData.txt"));
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
}
}
}
GeometricObject:
public abstract class GeometricObject {
//class variables
private String color;
private boolean filled;
//constructors
public GeometricObject() {
super();
color = "white";
filled = false;
}
public GeometricObject(String color, boolean filled) {
super();
this.color = color;
this.filled = filled;
}
//mutators
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
//user-defined methods
public abstract double getArea();
public abstract double getPerimeter();
#Override
public String toString() {
return super.toString() + " \tColor=" + this.getColor() + " \tFilled=" + this.isFilled();
}
}
Circle:
public class Circle extends GeometricObject {
//class variables
private double radius;
//constructors
public Circle() {
super();
radius = 1;
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
this.radius = radius;
}
//mutators
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//user-defined methods
#Override
public double getArea() {
//area of a circle
return (radius * radius * Math.PI);
}
#Override
public double getPerimeter() {
//perimeter of a circle
return (2 * radius * Math.PI);
}
#Override
public String toString() {
return super.toString() + "\nCircle: Radius=" + this.getRadius();
}
}
Rectangle:
public class Rectangle extends GeometricObject {
//class variables
private double height;
private double width;
//constructors
public Rectangle() {
super();
height = 1;
width = 1;
}
public Rectangle(double height, double width, String color, boolean filled) {
super(color,filled);
this.height = height;
this.width = width;
}
//mutators
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
//user-defined methods
#Override
public String toString() {
return super.toString() + "\nRectangle: Height=" + this.height + "\tWidth=" + this.width;
}
#Override
public double getArea() {
return (height * width);
}
#Override
public double getPerimeter() {
return (2 * height + 2 * width);
}
}
In your text file, you have special quotes around your shape items. This will make your life more difficult, so you should change that, if possible
Example of how to make objects (from your main method):
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
String[] parts = line.split(",");
if (parts[0].indexOf("Circle") != -1) {
Circle c = new Circle();
// ... parse the rest of the attributes to set up your circle
} else if ... // fill in the other shape cases
}

mass change values of arraylist

I have array list of circles, whitch are drawing by canvas. And everything is OK. But I need change all X,Y coordinates of circles, by during the program.
static ArrayList<Circle> mCircles;
private static void createCircles() {
if (mCircles == null) {
mCircles = new ArrayList<Circle>();
}
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
public static void AddCircle() {
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
private void Drawing(Canvas canvas) {
for (Circle c : mCircles) {
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mMalovani);
}
}
public static Circle findCircleClosestToTouchEvent(float x, float y) {
Circle c = mCircles.get(mCircles.size() - 1);
return c;
}
public class Circle extends Shape {
final float mRadius;
public Circle(float x, float y, float r) {
super(x, y);
mRadius = r;
}
final float getRadius() {
return mRadius;
}
}
public class Shape extends Activity {
protected float mStartX = 0f;
protected float mStartY = 0f;
public float mCurrentX = 30f;
public float mCurrentY = 30f;
protected float mActionDownX;
protected float mActionDownY;
protected float mActionMoveOffsetX;
protected float mActionMoveOffsetY;
// x y coordinate of a move action
public Shape (float x, float y) {
mStartX = x;
mStartY = y;
mCurrentX = x;
mCurrentY = y;
}
public void setStartX(float x) { mStartX = x; }
public void setStartY(float y) { mStartY = y; }
public float getCurrentX() { return mCurrentX; }
public float getCurrentY() { return mCurrentY; }
public void setCurrentX(float x) { mCurrentX = x;
}
public void setCurrentY(float y) { mCurrentY = y; }
public void setActionMoveOffsetX(float x) { mActionMoveOffsetX = x; }
public void setActionMoveOffsetY(float y) { mActionMoveOffsetY = y; }
public float getActionMoveOffsetX() { return mActionMoveOffsetX; }
public float getActionMoveOffsetY() { return mActionMoveOffsetY; }
public void setActionDownX(float x) { mActionDownX = x; }
public void setActionDownY(float y) { mActionDownY = y; }
public float getActionDownX() { return mActionDownX; }
public float getActionDownY() { return mActionDownY; }
public void restoreStartPosition() {
mCurrentX = mStartX;
mCurrentY = mStartY;
}
}
Assuming you have setCurrentX and setCurrentY methods opposite the getter methods, just loop through the list of circles.
private void changeCoordinates(List<Circle> circles, int x, int y){
for(Circle c:circles){
c.setCurrentX(x);
c.setCurrentY(y);
}
}

Categories

Resources