Bladeren bron

Refactors click on connection recognition, increases hitbox

Andreas T. Meyer-Berg 5 jaren geleden
bovenliggende
commit
f3d375f53d
1 gewijzigde bestanden met toevoegingen van 13 en 28 verwijderingen
  1. 13 28
      src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/VisualizationInteractor.java

+ 13 - 28
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/VisualizationInteractor.java

@@ -7,6 +7,7 @@ import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseMotionListener;
+import java.awt.geom.Line2D;
 import java.util.LinkedList;
 
 import javax.swing.JMenu;
@@ -585,34 +586,18 @@ public class VisualizationInteractor implements MouseInputListener,
 	 * @return true if point is on connection, else false
 	 */
 	private boolean pointOnConnection(int x, int y, Pair<Port, Port> p) {
-		//No valid connection part
-		if(p.getLeft()==null||p.getRight()==null||p.getLeft().getOwner()==null||p.getRight().getOwner()==null)
-			return false;
-		int lX = p.getLeft().getOwner().getX();
-		int lY = p.getLeft().getOwner().getY();
-		int rX = p.getRight().getOwner().getX();
-		int rY = p.getRight().getOwner().getY();
-		//Point out of bounds
-		if(x < Math.min(lX, rX) || x > Math.max(lX, rX) || y < Math.min(lY, rY) || y > Math.max(lY, rY))
-			return false;
-		double dLP = distance(lX,lY,x,y);
-		double dPR = distance(x,y,rX,rY);
-		double dLR = distance(lX,lY,rX,rY);
-		double diff = Math.abs(dLP+dPR-dLR);
-		return diff < 0.5;
-	}
-
-	/**
-	 * Calculates distance between (x1,y1) and (x2,y2)
-	 * 
-	 * @param x1 x Position of Point 1
-	 * @param y1 y Position of Point 1
-	 * @param x2 x Position of Point 1 
-	 * @param y2 y Position of Point 1
-	 * @return distance
-	 */
-	private double distance(int x1, int y1, int x2, int y2) {
-		return Math.sqrt(Math.pow(x1-x2, 2)+Math.pow(y1-y2, 2));
+		/** Filter invalid lines to prevent nullpointers */
+		if(p==null||p.getLeft()==null||p.getRight()==null||p.getLeft().getOwner()==null
+				||p.getRight().getOwner()==null)
+			return false;		
+		/** Number of pixels between click and connection, which should be recognized as click on the connection */
+		double hitBoxThreshold = 4;
+		/** Connection which might be clicked */
+		Line2D con = new Line2D.Float(p.getLeft().getOwner().getX(), p.getLeft().getOwner().getY(), p.getRight().getOwner().getX(), p.getRight().getOwner().getY());
+		/** Distance between click and connection */
+		double dist = con.ptSegDist(x, y);
+		/** Return true if within threshold */
+		return dist<hitBoxThreshold;
 	}
 
 	@Override