Here's some C++ code to solve the problem. I tried to not use references or static variables, to not confuse matters. But I couldn't get myself to not overload a few operators... Let me know if you have a hard time understanding what it's doing. But the function find_black_dot() is the key to it all, and it should be fairly easy to follow.
#include <iostream>
#include <cmath>
struct Vector {
float x, y;
Vector(float x, float y) : x(x), y(y) {
}
};
Vector operator*(Vector v, float s) {
return Vector(v.x*s, v.y*s);
}
float dot_product(Vector v, Vector w) {
return v.x*w.x + v.y*w.y;
}
Vector normalize(Vector v) {
return v * (1.0 / std::sqrt(dot_product(v, v)));
}
struct Point {
float x, y;
Point(float x, float y) : x(x), y(y) {
}
};
std::ostream &operator<<(std::ostream &os, Point p) {
return os << '(' << p.x << ',' << p.y << ')';
}
Vector operator-(Point p, Point q) {
return Vector(p.x-q.x, p.y-q.y);
}
Point operator+(Point p, Vector v) {
return Point(p.x+v.x, p.y+v.y);
}
struct Ray {
Point origin;
Vector direction;
Ray(Point origin, Vector direction) : origin(origin), direction(direction) {
}
};
// If dot_product(p-origin,normal)==constant, p is in the line
struct Line {
Vector normal;
float constant;
Line(Vector normal, float constant) : normal(normal), constant(constant) {
}
};
float find_intersection_parameter(Ray ray, Line line) {
return (line.constant - dot_product(ray.origin-Point(0.0f,0.0f), line.normal))
/ dot_product(ray.direction, line.normal);
}
Point find_black_dot(Point red_point, Point green_point) {
Line lines[4] = {
Line(Vector(1.0f,0.0f), 0.0f),
Line(Vector(1.0f,0.0f), 30.0f),
Line(Vector(0.0f,1.0f), 0.0f),
Line(Vector(0.0f,1.0f), 20.0f)
};
Ray ray(red_point, normalize(green_point-red_point));
double min_non_negative_intersection_parameter = 1.0e20f;
for (int i=0; i<4; ++i) {
float intersection_parameter = find_intersection_parameter(ray, lines[i]);
if (intersection_parameter >= 0.0f
&& intersection_parameter < min_non_negative_intersection_parameter)
min_non_negative_intersection_parameter = intersection_parameter;
}
return ray.origin + ray.direction * min_non_negative_intersection_parameter;
}
int main() {
Point red(16.5,10.5);
Point green(11.5,15.5);
std::cout << find_black_dot(red, green) << '\n';
}