Intersection Operator richtig?



  • Hi! Ich hab für meine Klasse einen Operator geschrieben, der schauen soll, ob
    zwei Rechtecke in irgendeinem Punkt überschneiden.

    Mein Test funktioniert nicht und ich bin mir nicht sicher, ob dieser Code richtig ist!

    public static Boolean operator /(Dimension a, Dimension b)
            {
                if (a.Left < b.Right)
                {
                    if (a.Bottom > b.Top || a.Top < b.Bottom) return true;
                }
                if (a.Right > b.Left)
                {
                    if (a.Bottom > b.Top || a.Top < b.Bottom) return true;
                }
    
                if (a.Bottom > b.Top)
                {
                    if (a.Right > b.Left || a.Left < b.Right) return true;
                }
                if (a.Top < b.Bottom)
                {
                    if (a.Right > b.Left || a.Left < b.Right) return true;
                }
                return false;
            }
    


  • Nein, der Test ist falsch. Schau dir mal die Bedingung an:

    if (a.Left < b.Right)
                {
                    if (a.Bottom > b.Top || a.Top < b.Bottom) return true;
                }
    

    Sagen wir mal a geht von (0, 0) bis (1, 1), und b geht von (100, 100) bis (101, 101).

    if (a.Left < b.Right)  // True: 0 < 101
                {
                    if (a.Bottom > b.Top || a.Top < b.Bottom /* True: 0 < 101*/) return true;
                }
    

    Der Test liefert also true zurueck, obwohl a und b sich nicht ueberschneiden.

    Richtig muss es in etwa so ausschauen:

    if (a.right < b.left || b.left < a.right)
    	{
    		return false; // keine horizontale Ueberlappunt moeglich
    	}
    
    	if (b.bottom < a.top || b.bottom < a.top)
    	{
    		return false; // keine vertikale Ueberlappung moeglich
    	}
    
    	// Kollision!
    	return true;
    }
    

    Die Ueberschneidung als Operator zu implementieren, finde ich persoenlich uebrigens sehr schlechten Stil!


Anmelden zum Antworten