Skip to content

Instantly share code, notes, and snippets.

@sebingel
Created September 12, 2016 11:51
Show Gist options
  • Save sebingel/ef4ff622d6c1e58d8a4728995cf27210 to your computer and use it in GitHub Desktop.
Save sebingel/ef4ff622d6c1e58d8a4728995cf27210 to your computer and use it in GitHub Desktop.
Calculates the intersection of a vector (given by two points) with a circle (point and radius)
using System;
using System.Drawing;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
Point start = new Point(0, 0);
Point end = new Point(100, 12);
Point circle = new Point(50, 0);
double radius = 10;
double a = Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2);
double b = 2 * (end.X - start.X) * (start.X - circle.X) + 2 * (end.Y - start.Y) * (start.Y - circle.Y);
double c = Math.Pow(start.X - circle.X, 2) + Math.Pow(start.Y - circle.Y, 2) - Math.Pow(radius, 2);
double t = (2 * c) / (-b + Math.Sqrt(Math.Pow(b, 2) - 4 * a * c));
Console.WriteLine($"root: {t}");
int tx = (int)Math.Round((end.X - start.X) * t + start.X);
int ty = (int)Math.Round((end.Y - start.Y) * t + start.Y);
Console.WriteLine($"intersection: {tx},{ty}");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment