Stuck with trying to remove points close to the edge, how can I do this?

I have a problem, I’m trying to remove “stations” or points less than a certain length from the edge, let’s say, 120px from the edge. Now, I tried using a function that removes the stations if they get too close, but that didn’t work. So now, I’m a bit confused as to what to do.

https://editor.p5js.org/IamRifki/sketches/ozXCkoPhF

I’ve had to make a lot of inferences about what exactly you are trying to do, but I’m seeing two issues:

  1. When you are randomly generating stations, you are assigning them by index. This makes a sparse array. That is, an array with values for certain indices but not for other indices (for example you might have any array with values at only array[3] and array[7] and this would have a length of 8 but it would not have values at any other positions. I.e. array[0] would return undefined). The result of this is that you get errors because you try to reference properties on the station variable when it is undefined.
      // This makes a sparse matrix
      if (bounds)
        gridStations[j * grid + i] = new Station(point);

This is were you get an error:

      // Because gridStations is sparse, station will sometimes be undefined
      let station = gridStations[int(random(gridStations.length))];

      // code that assumes station is not null or undefined...

Because you are only getting stations randomly I think you can simply add new stations to the end of the array using gridStations.push(...).

  1. The parameters you are passing to the pointInRectBounds function do not make sense:
      let bounds = pointInRectBounds(
        point[0],
        point[1],
        // left
        width - (width / grid + 1),
        // top
        height - (height / grid + 1),
        // width
        width - (width - (width / grid + 1)),
        // height
        height - (height - (height / grid + 1))
      );

if you are trying to avoid placing stations within one grid box of the edge, then the left value you want is just the width of a single grid square: width / grid, likewise the top of your bounding box will be the height if a single grid square height / grid. The width and height of your bounding box will bet two grid squares less then the total dimension (i.e. width - 2 * (width / grid)). Here’s what I think you would want:

      let bounds =
          pointInRectBounds(
            point[0],
            point[1],
            width / grid,
            height / grid,
            width - (width / grid) * 2,
            height - (height / grid) * 2
          );
2 Likes