I have an assignment explaining like this:
Write a definition of a class named Point that might be used to store and manipulate the location of a point on the plane. The point is stored as two coordinates: x and y. You will need to declare and implement the following methods:
Two constructors:
a. no-argument constructor that sets the point coordinates to (0,0), and
b. a constructor that takes x and y coordinate of the point and sets member
variables.
Method set that sets the private data after an object of this class is created.
A method to move the point by an amount along the vertical and horizontal directions specified by the first and second arguments: move(double dx, double dy)
The method to rotate the point by 90 degrees clockwise around the origin. Hint: when point is getting rotated 90 clockwise around the origin the following changes happen to its coordinates: xrotated = y; yrotated = -x .
two accessor methods to retrieve the coordinates of the point.
It should be 2 different call. these items on second one (not main class)
I will call this on main class. (I do that).
This is my code but I dont understand what I should do next.
private double x;
private double y;
public Point(double initialX, double initialY) {
x = initialX;
y = initialY;
}
public Point() {
x = 0;
y = 0;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void move(double dx, double dy) {
x += dx;
y += dy;
}
You have almost everything, good job. For the rotate by 90 function, you're given a pretty good clue about what to do. Imagine you have a point (1,2), and you rotate it. you'll end up with (2,-1). if you rotate it again, you'll get (-1,-2). once more gives you (-2,1), and a fourth 90 degree rotation gives (1,2), which is what you started with. come up with a function that does this. It shouldn't be longer than 3 lines.
The setter functions (functions used to set, or change, the values) are simply functions you can use to set the values of the point. so, you'd have a function "setX(...) { ... }" and a function "setY(...) { ... }". These should be very straightforward.
Feel free to ask further questions if you're still confused.
private double x;
private double y;
public Point(double dx, double dy) {
x = dx;
y = dy;
}
public Point() {
x = 0;
y = 0;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void SetX(double dx)
{
x = dx;
}
public void SetY(double dy)
{
y = dy;
}
public void move(double dx, double dy)
{
x = x + dx;
y = y + dy;
}
public double rotateX()
{
double temp = x;
x=y;
y=temp;
return x;
}
public double rotateY()
{
y=-y;
return y;
}
main page
public static void main(String[] args) {
// TODO Auto-generated method stub
Point p = new Point();
p.SetX(50);
p.SetY(17);
System.out.println("X and Y coordinates are : \n("+p.getX()+","+p.getY()+")");
System.out.println("after 90 degree clockwise rotate: ");
System.out.println(p.rotateX()+","+p.rotateY());
Related
I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}
This is my test class,
public class Shape2DTester {
public static void main(String[] args) {
GeometricObject2D geoObject1 = new ComparableCircle2D(0, 5, 2);
GeometricObject2D geoObject3 = new ComparableCircle2D(0, 0, 2);
System.out.println("geoObject1 overlaps geoObject3: "
+ geoObject1.intersect(geoObject3));
}
}
This is my circle class,
public class ComparableCircle2D extends GeometricObject2D<ComparableCircle2D> {
public double x, y;
public double radius;
ComparableCircle2D() {
super();
this.radius = 1.0;
}
ComparableCircle2D(double radius) {
super();
this.radius = Math.abs(radius);
}
ComparableCircle2D(double x, double y, double radius) {
super(x, y);
this.radius = Math.abs(radius);
}
public double getArea() {
return Math.PI * getRadius() * getRadius();
}
public double getPerimeter() {
return 2 * Math.PI * getRadius();
}
public void setRadius(double setRadius) {
this.radius = Math.abs(setRadius);
}
public double getRadius() {
return radius;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - getX();
double dy = other.y - getY();
double radi = other.radius + getRadius();
return (dx * dx + dy * dy < radi * radi);
}
}
}
this is my superclass,
public abstract class GeometricObject2D<T extends GeometricObject2D> implements
Comparable<GeometricObject2D> {
public double x, y;
GeometricObject2D() {
this.x = 0;
this.y = 0;
}
GeometricObject2D(double x, double y) {
this.x = x;
this.y = y;
}
public abstract double getArea();
public abstract double getPerimeter();
public abstract boolean intersect(GeometricObject2D g);
#Override
public int compareTo(GeometricObject2D o) {
// TODO Auto-generated method stub
return 0;
}
}
I want to find out possibility of intersecting two circles but there is an error in my code that I didn't realize.
For example I create two circle object coordinates-1(0,0) , radius-1=2 and coordinates-2(0,5) ,radius-2=2. That above method must return false but returns true. I didn't find error.
System.out.println("geoObject1 intersects geoObject3: "
+ geoObject1.intersect(geoObject3));
prints geoObject1 intersects geoObject3: true
As #Pshemo said, your code (now that you've shown it) has an extra } at the end that shouldn't be there.
How, if we paste all that code into IDEONE, and run it, we confirm your error.
If we then DEBUG the code by adding a single print statement, we see:
dx=0.0, dy=0.0, radi=4.0
Hmmm, why is dy = 0 when it should be 5?
Answer: Because you added another set of x and y fields to your subclass, that is hiding the fields from the base class!!!!
Simple debugging would have shown you this yourself. This is what #PeterLawrey was talking about in his comment:
you mistake is it is likely to be; the values are not what you think they are. This is where debugging your code can show this.
Of course, if you had used a good IDE, you wouldn't even need to debug, because the IDE would have warned you about the field hiding.
Rather than Math.pow(x, 2) it is more efficient to do x * x, and instead of using Math.sqrt you can square the sum of the radii.
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - x; // e.g. 0 - 0
double dy = other.y - y; // e.g. 5 - 0
double radii = other.radius + radius; // e.g. 2 + 2
return dx * dx + dy * dy < radii * radii ; // e.g. 0 + 25 < 16 is false.
}
You never assign the fields x and y. Therefore dx = dy = 0.
You have to either assign the field's values or use the fields in the superclass (but you shouldn't have fields with the same information in the same object, so remove the fields created in ComparableCircle2D).
Also if your circle is defined as contour, not as area, then the test for intercepting circles is incorrect. Consider the case where 2 circles with the same center have different radii: dx² + dy² = 0 < dr², but the contours don't intersect; only the areas inside the circles overlap.
So I am trying to move a projectile in the direction that is indicated by the mouse position on the screen. I already have converted the mouse coordinates into in-game coordinates however I can't figure out how to correctly move the projectile into the proper direction. I am trying to use a slope to move the projectile but it doesn't seem to want to grab the correct slope so I end up with them flying in completely wrong directions. Here are some bits of code that I am using.
Any help on this would be greatly appreciated as I am a little over my head in this.
NOTE: The projectile does NOT follow the mouse. It should save the coordinates and then head in that direction noting that it can also go past the given coordinates at the same rate.
Entity Creation
int[] mousePos = MouseManager.getCalculatedMouseCoordinates();
float deltaX = mousePos[0] - GameManager.x;
float deltaY = mousePos[1] - GameManager.y;
float m = deltaY/deltaX;
System.out.println(m);
GameManager.currentWorld.addEntity(new EntityProjectile(GameManager.x, GameManager.y, 30, m, 50, "fireball"));
Projectile Class
package UnNamedRpg.Player.Entity;
public class EntityProjectile {
private double x, y;
private int entityID = -1;
private int speed;
private double headerX, headerY;
private int renderHeading;
private double range, currentRange = 0;
private String texture;
private double factor = -1;
public EntityProjectile(double startX, double startY, int speed, double headerX, double headerY, double range, String texture){
setX(startX);
setY(startY);
setSpeed(speed);
setHeaderX(headerX);
setHeaderY(headerY);
setTexture(texture);
setRange(range);
}
public void doTick(){
double vx = this.x - this.headerX;
double vy = this.y - this.headerY;
if(this.factor == -1){
double length = Math.sqrt((vx*vx) + (vy*vy));
double factor = this.speed / length;
this.factor = factor;
}
vx *= factor;
vy *= factor;
this.x = vx;
this.y = vy;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getRenderHeading() {
return renderHeading;
}
public void setRenderHeading(int renderHeading) {
this.renderHeading = renderHeading;
}
public int getEntityID() {
return entityID;
}
public void setEntityID(int entityID) {
this.entityID = entityID;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public String getTexture() {
return texture;
}
public void setTexture(String texture) {
this.texture = texture;
}
public double getRange() {
return range;
}
public void setRange(double range) {
this.range = range;
}
public double getCurrentRange() {
return currentRange;
}
public void setCurrentRange(double currentRange) {
this.currentRange = currentRange;
}
public double getHeaderX() {
return headerX;
}
public void setHeaderX(double headerX) {
this.headerX = headerX;
}
public double getHeaderY() {
return headerY;
}
public void setHeaderY(double headerY) {
this.headerY = headerY;
}
public double getFactor() {
return factor;
}
public void setFactor(double factor) {
this.factor = factor;
}
}
Update Position Method
--Now called in EntityProjectile class every tick instead of it happening in the world tick.
Moving towards a given point is relatively simple with some basic vector math. The vector you want to move along is calculated simply by coordinate subtraction:
vx = objectX - mouseX
vy = objectY - mouseY
But you probably want to move your object a little slower than bam there, so you need to scale the vector to a desired length (equals speed per game tick). The current length of the vector is obtained by the pythagorean sqrt(a * a + b * b). To scale the vector to a given length just multiply the components by the required factor:
double targetLength = 5.0; // chosen arbitrarily
double length = Math.sqrt(vx * vx + vy * vy);
double factor = targetLength / length;
vx *= factor;
vy *= factor;
There you have your speed components x,y to be used as delta per game tick. The 5.0 is the "speed" at which the object will move per tick.
EDIT: #Cyphereion About the length of the vector, thats geometrically speaking the base of a triangle, see https://en.wikipedia.org/wiki/Pythagorean_theorem (considered common knowlegde).
Once you have that, you just need to adjust the length of each component by figuring out a scaling factor that makes the base line come out as the desired "speed" length. The original values of the components (vx, vy) represent a vector (see: https://en.wikipedia.org/wiki/Euclidean_vector#Representations) encoding the direction to move to.
Scaling the vector's length adjusts the speed at which your object moves when you apply the vectors components as delta to its position (which is just vector addition). I swapped around the division length/targetLength initailly (now fixed), so the speed variable had a reversed meaning (larger = slower instead of larger = faster).
If you're having trouble with your sprite then use the setDirection() you have there to augment the trajectory. In these examples you have all good code but you're missing restting the direction when your mouse changes direction. That's all I can see. Good luck!
How can I write a double slope method for a segment class?
I have two variable: p1 = x1, y1 and p2 = x2, y2.
I did this code but this is wrong:
public double slope() {
return (double)(p2.y - p1.y)/(p1.x-p2.x);
}
Can someone tell me why is it wrong?
What is the right way to write it?
Thank you!
Depending on the type of p1, it could be a Point which takes both an x and a y coordinate.
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
You'd have to use getX() and getY() to get the X and Y coordinates. You'd also have to be sure you created the point with new Point(1, 2) as well.
Also, be sure that you're getting the right cast behavior by adding parens around it and your numerator:
return ((double)(p2.getY() - p1.getY()))/(p1.getX() - p2.getX());
(Although that above seems to scream for a deltaY and deltaX method alone)
So in my programming class we are learning to use draw classes. Basically draw a line and stuff and we did a y=mx+b line in class.
I wanted to jump ahead and start doing more crazy mathematical ones!
I'm having trouble using this one though, which I found on the U of Princeton website.
public class Spiral {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // # sides if decay = 1.0
double decay = Double.parseDouble(args[1]); // decay factor
double angle = 360.0 / N;
double step = Math.sin(Math.toRadians(angle/2.0));
Turtle turtle = new Turtle(0.5, 0.0, angle/2.0);
for (int i = 0; i < 10*N; i++) {
step /= decay;
turtle.goForward(step);
turtle.turnLeft(angle);
}
}
}
import java.awt.Color;
public class Turtle {
private double x, y; // turtle is at (x, y)
private double angle; // facing this many degrees counterclockwise from the x-axis
// start at (x0, y0), facing a0 degrees counterclockwise from the x-axis
public Turtle(double x0, double y0, double a0) {
x = x0;
y = y0;
angle = a0;
}
// rotate orientation delta degrees counterclockwise
public void turnLeft(double delta) {
angle += delta;
}
// move forward the given amount, with the pen down
public void goForward(double step) {
double oldx = x;
double oldy = y;
x += step * Math.cos(Math.toRadians(angle));
y += step * Math.sin(Math.toRadians(angle));
StdDraw.line(oldx, oldy, x, y);
}
// pause t milliseconds
public void pause(int t) {
StdDraw.show(t);
}
public void setPenColor(Color color) {
StdDraw.setPenColor(color);
}
public void setPenRadius(double radius) {
StdDraw.setPenRadius(radius);
}
public void setCanvasSize(int width, int height) {
StdDraw.setCanvasSize(width, height);
}
public void setXscale(double min, double max) {
StdDraw.setXscale(min, max);
}
public void setYscale(double min, double max) {
StdDraw.setYscale(min, max);
}
// sample client for testing
public static void main(String[] args) {
double x0 = 0.5;
double y0 = 0.0;
double a0 = 60.0;
double step = Math.sqrt(3)/2;
Turtle turtle = new Turtle(x0, y0, a0);
turtle.goForward(step);
turtle.turnLeft(120.0);
turtle.goForward(step);
turtle.turnLeft(120.0);
turtle.goForward(step);
turtle.turnLeft(120.0);
}
}
Turtle uses this class: StdDraw which is just way too many lines of code for me to paste here.
I keep getting an error when I go to execute spiral:
java.lang.ArrayIndexOutOfBoundsException: 0
at Spiral.main(Spiral.java:4)
Not sure why. Can anyone help me out so I can play around with this?
Did you specify two command-line arguments? It looks like it takes the number of steps and the decay as a parameter and will crash if you don't specify these.
For example:
java Spiral 10 1.1