发不了图片,我描述吧
有个正方形,边长已知,其中心点A坐标已知(X,Y),正方形外有个随机的B点坐标已知(X1,Y1)
求问AB点连线与正方形相交的坐标怎么算?
写程序的时候需要这个逻辑,本人数学真的忘差不多了。冰天雪地,跪求强人
------解决方案--------------------
设交点为M(xm,ym),N(xn,yn)
条件一,交点M、N在正方形上,符合正方形的函数(根据边长、A点可求出)
条件二,M、N在AB确定的直线上,符合AB线性函数(有AB坐标可以求出)
列方程组求解
------解决方案--------------------
假设这个正方形的边与坐标轴是平行的
正方形边长不妨设为 2a
因:正方形中心坐标为(x, y)
故:其四点坐标分别为(x-a,y-a),(x-a,y+a),(x+a,y-a),(x+a,y+a)
(x,y)与(x1,y1)的连线与正方形交点必在正方形上,即交点的横(纵)坐标可知
如:交点在正方形的右边上,则有:
y-a <= (y1-y)/(x1-x)*a + y <= y+a;
其他类推即可通过4次判断内得出交点坐标
------解决方案--------------------
- Java code
class Point { private double x; private double y; public Point() { } /** * @param x * @param y */ public Point(double x, double y) { this.x = x; this.y = y; } /** * @return the x */ public double getX() { return x; } /** * @param x * the x to set */ public void setX(double x) { this.x = x; } /** * @return the y */ public double getY() { return y; } /** * @param y * the y to set */ public void setY(double y) { this.y = y; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]"; }}public class Test { public static double getK(Point a, Point b) { if (b.getX() == a.getX()) { return 0; } return (b.getY() - a.getY()) / (b.getX() - a.getX()); } public static Point getPoint(Point a, Point b, Point c, Point d) { Point result = new Point(); double k1, k2; k1 = (b.getY() - a.getY()) / (b.getX() - a.getX()); k2 = (d.getY() - c.getY()) / (d.getX() - c.getX()); result.setX((k1 * a.getX() / k2 - c.getX()) * k2 / (k1 - k2)); result.setY(k1 * (result.getX() - a.getX())); return result; } public static Point[] getPoint(Point a, Point b, double len) { Point[] result = new Point[] { new Point(), new Point() }; double k = getK(b, a); double z = a.getY() - k * a.getX(); if (k >= -1.0 && k <= 1.0) { result[0].setY(a.getY() + len / 2); result[0].setX((result[0].getY() - z) / k); result[1].setY(a.getY() - len / 2); result[1].setX((result[1].getY() - z) / k); } else { result[0].setX(a.getX() + len / 2); result[0].setY(result[0].getX() * k + z); result[1].setX(a.getX() - len / 2); result[1].setY(result[1].getX() * k + z); } return result; } public static void main(String[] args) { Point a = new Point(2, 2); Point b = new Point(5, 4); double len = 2.0; Point[] points = getPoint(a, b, len); for (Point p : points) { System.out.println(p); } }}