/// <summary> /// Tests if a segment intersects a rectangle</summary> /// <param name="seg">The segment</param> /// <param name="rect">Rectangle, in Windows coordinates, such that the top y has /// a lower value than the bottom Y</param> /// <returns>True iff the segment intersects the rectangle</returns> public static bool Intersects(Seg2F seg, RectangleF rect) { // Quick acceptance if (rect.Contains(seg.P1) || rect.Contains(seg.P2)) { return(true); } // Check if both segment points are on same side of rectangle. if (seg.P1.X < rect.Left && seg.P2.X < rect.Left) { return(false); } if (seg.P1.Y < rect.Top && seg.P2.Y < rect.Top) { return(false); } if (seg.P1.X > rect.Right && seg.P2.X > rect.Right) { return(false); } if (seg.P1.Y > rect.Bottom && seg.P2.Y > rect.Bottom) { return(false); } // Check if all four rectangle points are on the same side of the line. Vec2F dir = new Vec2F(seg.P2.X - seg.P1.X, seg.P2.Y - seg.P1.Y); if (dir.LengthSquared > Seg2F.DegenerateLength * Seg2F.DegenerateLength) { Vec2F normal = dir.Perp; float dot1 = Vec2F.Dot(new Vec2F(rect.Left, rect.Top) - seg.P1, normal); float dot2 = Vec2F.Dot(new Vec2F(rect.Right, rect.Top) - seg.P1, normal); if (dot1 * dot2 > 0) // both are < 0 or both are > 0 { dot2 = Vec2F.Dot(new Vec2F(rect.Left, rect.Bottom) - seg.P1, normal); if (dot1 * dot2 > 0) // both are < 0 or both are > 0 { dot2 = Vec2F.Dot(new Vec2F(rect.Right, rect.Bottom) - seg.P1, normal); if (dot1 * dot2 > 0) // both are < 0 or both are > 0 { return(false); } } } } // Must intersect. return(true); }
/// <summary> /// Returns the angle to the vector v in radians /// </summary> /// <param name="v">Vector v</param> public double AngleToRAD(Vec2F v) { Vec2F n1 = new Vec2F(x, y); Vec2F n2 = new Vec2F(v); n1.Normalize(); n2.Normalize(); double ndn = n1.Dot(n2); if (ndn < -1) { ndn = -1; } if (ndn > 1) { ndn = 1; } return(Math.Acos(ndn)); }