我有一个简单的类 2Dpoints,有两个字段,x 和 y。我想编写一个代码,以便我可以命令一个点缓慢移动到另一个点,就像它在它们距离的矢量线上移动一样。但我不知道怎么办?
我首先想到它应该包含一个 for 循环,以便它知道,它应该移动直到到达另一点
类似于 for(int d=0 ; dimport 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));
}
}
答案 0 :(得分:0)
我已经评论了主要内容:
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));
}
}
}
答案 1 :(得分:0)
@AlexanderAlexandrov 我已经将变量的类型相应地更改为双倍,现在在我的一个类中,我有一个方法 givePoints,它使用 Scanner 询问用户他想要多少点以及坐标是什么,然后它会保存它们变成一个点数组,第一个元素总是(0,0)。 另一种方法将一组点作为参数,并按照它们到 point(0,0) 的距离的顺序对它们进行排序。 这些方法效果很好。问题在于方法hitThepoints。 在这里,我想首先创建点数组,对它们进行排序,然后命令我的机器人击中所有点。 Robot 是 Robot extends circle 类的对象,位置类型为 Point,首先是在 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());
}
}
}