public float DistanceToSquared(ref Vector3 vector, out Segment connectingSegment) { float segmentLength = (float)this.GetLength(); Vector2 normalizedLine = new Vector2( (float)(Point2.X - Point1.X) / segmentLength, (float)(Point2.Y - Point1.Y) / segmentLength); Vector2 pointVector = new Vector2((float)(vector.X - Point1.X), (float)(vector.Y - Point1.Y)); float length = Vector2.Dot(pointVector, normalizedLine); if (length < 0) { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = Point1; return((float)connectingSegment.GetLengthSquared()); } else if (length > segmentLength) { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = Point2; return((float)connectingSegment.GetLengthSquared()); } else { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = new Point(Point1.X + length * normalizedLine.X, Point1.Y + length * normalizedLine.Y); return((float)connectingSegment.GetLengthSquared()); } }
public float DistanceToSquared(ref Vector3 vector, out Segment connectingSegment) { float segmentLength = (float)this.GetLength(); Vector2 normalizedLine = new Vector2( (float)(Point2.X - Point1.X) / segmentLength, (float)(Point2.Y - Point1.Y) / segmentLength); Vector2 pointVector = new Vector2((float)(vector.X - Point1.X), (float)(vector.Y - Point1.Y)); float length = Vector2.Dot(pointVector, normalizedLine); if (length < 0) { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = Point1; return (float) connectingSegment.GetLengthSquared(); } else if (length > segmentLength) { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = Point2; return (float) connectingSegment.GetLengthSquared(); } else { connectingSegment.Point1 = new Point(ref vector); connectingSegment.Point2 = new Point(Point1.X + length * normalizedLine.X, Point1.Y + length * normalizedLine.Y); return (float)connectingSegment.GetLengthSquared(); } }