C-sharp:Intersection Tests
Aus Weis nix
Simple 2D intersection tests can be used in many cases to add interactive components. Here we use the Vector2 class from the XNA toolkit as 2D-position container.
namespace Utilities { using System; using Microsoft.Xna.Framework; class IntersectionTest { /// <summary> /// 2D Check if a circle is within another circle /// If the circles touch on a single point, they are /// considered intersecting. /// </summary> /// <param name="centerA">Center of first circle.</param> /// <param name="radiusA">Radius of first circle.</param> /// <param name="centerB">Center of second circle.</param> /// <param name="radiusB">Radius of second circle.</param> /// <returns> /// A boolean flag indicating if the circles intersect. /// </returns> public static bool CircleInCircle(Vector2 centerA, double radiusA, Vector2 centerB, double radiusB) { double dX = (double)(centerB.X - centerA.X); double dY = (double)(centerB.Y - centerA.Y); double d = Math.Sqrt(dX * dX + dY * dY); // circles do not intersect if they are too far apart if (d > (radiusA + radiusB)) { return false; } return true; } /// <summary> /// 2D Check if a point lies withing a polygon. /// </summary> /// <param name="polygonVertex">The points of the polygon.</param> /// <param name="testVertex">The point to check.</param> /// <returns> /// A boolean flag indicating if the test vertex /// is inside the polygon. /// </returns> public static bool PointInPolygon(Vector2[] polygonVertex, Vector2 testVertex) { bool c = false; int nvert = polygonVertex.Length; if (nvert > 2) { int i, j; for (i = 0, j = nvert - 1; i < nvert; j = i++) { if (((polygonVertex[i].Y > testVertex.Y) != (polygonVertex[j].Y > testVertex.Y)) && (testVertex.X < (polygonVertex[j].X - polygonVertex[i].X) * (testVertex.Y - polygonVertex[i].Y) / (polygonVertex[j].Y - polygonVertex[i].Y) + polygonVertex[i].X)) { c = !c; } } } return c; } } }
