Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created November 16, 2025 04:36
Show Gist options
  • Select an option

  • Save abikoushi/070279fa3ffe9bd79808e3c32adaa1e2 to your computer and use it in GitHub Desktop.

Select an option

Save abikoushi/070279fa3ffe9bd79808e3c32adaa1e2 to your computer and use it in GitHub Desktop.
2点を結ぶとき線分が多角形の境界をまたぐかの判定
#ref https://qiita.com/zu_rin/items/e04fdec4e3dec6072104
Judge <- function(a, b, c, d) {
s = (a$x - b$x) * (c$y - a$y) - (a$y - b$y) * (c$x - a$x);
t = (a$x - b$x) * (d$y - a$y) - (a$y - b$y) * (d$x - a$x);
if (s * t > 0){
return(FALSE)
}
s = (c$x - d$x) * (a$y - c$y) - (c$y - d$y) * (a$x - c$x);
t = (c$x - d$x) * (b$y - c$y) - (c$y - d$y) * (b$x - c$x);
if (s * t > 0){
return(FALSE)
}
return(TRUE)
}
crossborder <- function(seg, df_v){
seg = simplify2array(seg)
a = as.list(seg[1,])
b = as.list(seg[2,])
logi = FALSE
for(i in seq_len(nrow(df_v)-1L)){
c = as.list(df_v[i,])
d = as.list(df_v[i+1,])
logi = logi | Judge(a,b,c,d)
if(logi){
return(TRUE)
}
}
c = as.list(df_v[nrow(df_v),])
d = as.list(df_v[1,])
logi = logi | Judge(a,b,c,d)
return(logi)
}
df_v <- data.frame(
x = c(1:9, 8:1),
y = c(1, 2*(5:3), 2, -1, 17, 9, 8, 2:9)
)
plot(range(polygon$x), range(polygon$y), type = "n", xlab="x", ylab="y")
polygon(polygon$x, polygon$y, col = "orange", lty = 2, lwd = 2, border = "red")
seg1 <- locator(2)
segments(x0 = seg1$x[1], y0 = seg$y[1], x1 = seg1$x[2], y1 = seg1$y[2], lty=2)
crossborder(seg1, df_v)
seg2 <- locator(2)
segments(x0 = seg2$x[1], y0 = seg2$y[1], x1 = seg2$x[2], y1 = seg2$y[2], lty=2)
crossborder(seg2, df_v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment