判断点是否在矩形框内 - Luomusha/blog GitHub Wiki

判断点是否在矩形框内

数据格式

export type Coordinate = {
  x: number;
  y: number;
}

export type Unit = {
  x: number
  y: number
  width: number
  height: number
  radius: number
  rotate: number
}

export const isPointInRect = (point: Coordinate, unit: Unit) => {
    const vx = point.x - unit.x
    const vy = point.y - unit.y
    const x = vx * Math.cos(-unit.rotate) - vy * Math.sin(-unit.rotate)
    const y = vy * Math.cos(-unit.rotate) + vx * Math.sin(-unit.rotate)    
    return 0 < x && x < unit.width && 0 < y && y < unit.height
}

原理

二维直角坐标系中,一个矩形,定点A(x0,y0),宽度widht,高度height,旋转倾角rotate,判断点P(x,y)是否在举行框内

picture (1)

解答思路

连接AP,计算向量AP(x-x0, y-y0) 设想以A点为原点rotate为方向构建直角坐标系。

p2

即可判断AP的x是否在0~width范围内,AP的y是否在0~height内来判断是否在矩形内了。

所以将图形逆向旋转,找到映射点P'

picture (2)

const x = vx * Math.cos(-unit.rotate) - vy * Math.sin(-unit.rotate)
const y = vy * Math.cos(-unit.rotate) + vx * Math.sin(-unit.rotate)   

然后判断P'(x, y)是否在矩形内即可。