R/rectangles.R

Defines functions rects

Documented in rects

#' Genereate rectangle corner coordinates
#'
#' Returns corner coordinates for a rectangle parameterise by its center (x,y),
#' angle of rotation (measured from positive x in radians), length and width.
#' Coordinates are labelled P1 to P4 from top right and moving clockwise
#'
#'                    Length
#'    P4------------------------------------P1
#'    |                                      |
#'    |                                      |  Width
#'    |                                      |
#'    P3------------------------------------P2
#'
#'
#' @param x Rectangle centre x coordinate
#' @param y Rectangle centre y coordinate
#' @param angle Rectangle angle of rotation (measured from positive x in radians)
#' @param length Rectangle length
#' @param width Rectangle width
#'
#' @return A dataframe of the 4 corner coordinates
#' @export
rects <- function(x, y, angle, length, width){

  # Compute x_start and x_end of each rectangle (assuming zero width)
  xs <- x - cos(angle) * length/2
  xe <- x + cos(angle) * length/2
  ys <- y - sin(angle) * length/2
  ye <- y + sin(angle) * length/2

  # Compute the x and y coordinates of the 4 corners of the rectangle when the
  # width is considered.
  p1x <- xe - ((width/2) * cos((pi/2) - angle))
  p1y <- ye + ((width/2) * sin((pi/2) - angle))

  p2x <- xe + ((width/2) * cos((pi/2) - angle))
  p2y <- ye - ((width/2) * sin((pi/2) - angle))

  p3x <- xs + ((width/2) * cos((pi/2) - angle))
  p3y <- ys - ((width/2) * sin((pi/2) - angle))

  p4x <- xs - ((width/2) * cos((pi/2) - angle))
  p4y <- ys + ((width/2) * sin((pi/2) - angle))

  data.frame(p1x = p1x, p1y = p1y,
             p2x = p2x, p2y = p2y,
             p3x = p3x, p3y = p3y,
             p4x = p4x, p4y = p4y)
}
dickie-roper/lcdiagrammer documentation built on Nov. 4, 2019, 10:31 a.m.