0
votes

I created a canvas to draw on. I draw some rectangle objects

class Rectangle extends Shape{
    constructor(posTopLeft, width, height){
    const halfWidth = width * 0.5;
    const halfHeight = height * 0.5;

    super(width, height, new Position(posTopLeft.x + halfWidth, posTopLeft.y + halfHeight)); // set width, height and center position

    this.centerLeftPosition = new Position(this.centerPosition.x - halfWidth, this.centerPosition.y);
    this.centerRightPosition = new Position(this.centerLeftPosition.x + width, this.centerLeftPosition.y);
    this.centerTopPosition = new Position(this.centerPosition.x, this.centerPosition.y - halfHeight);
    this.centerBottomPosition = new Position(this.centerPosition.x, this.centerTopPosition.y + height);

    this.topLeftPosition = posTopLeft;
    this.bottomLeftPosition = new Position(this.topLeftPosition.x, this.topLeftPosition.y + height);
    this.topRightPosition = new Position(this.topLeftPosition.x + width, this.topLeftPosition.y);
    this.bottomRightPosition = new Position(this.topRightPosition.x, this.bottomLeftPosition.y);
  }
}

rect

I also want to draw a line from one rectangle to another.

class Lane{
    constructor(startRect, targetRect){
       this.startRect = startRect;
       this.targetRect = targetRect;
  }
}

How can I connect these two rectangles by a lane if the lane tries to calculate the shortest path?

Means if one rect is exactly above the other one the lane would go from center bottom from the first rect to center top from the second rect.

If the first rect is on the left and the second is on the right, the lane would go from center right to center left of the other rect.

1
Check all possible connections and find the shortestBen West

1 Answers

0
votes

just calculate the distance from every point of one rect to every point of the other rect, then you sort the list and take the shortest one

so you would for example have two lists one for all the points in a rect - now you iterate over the first list and for every point you calculate the distance to all points of the other rectanlge

rectangle1[].foreach(function(point) {
distances.push(getDistance(point, point));
});

and then you just distances.sort() to get the shortest one

to know which one that was you can either save an object in distances that contains the coords or names of the other points or you make a dictionary where you save what distance corresponds to what names - for the later one you just have to handle cases where the distances of multiple points are equal seperately, whereas for the first one you probs cant just sort something like {42, {pointA: [32,12], pointB: [42, 64]}} so you will have to write a func that collects the distances and then does that

both are in the end the same, hope i could help, cheers