碰撞检测系列——线与矩形碰撞/相交

此文章是碰撞检测系列的第十篇,线和矩形碰撞检测/相交,此系列主要包含了多种形状的碰撞/相交检测方法。

预览

先查看效果吧,点击这里

碰撞/相交检测方法

一条线与矩形是否碰撞/相交,可以理解成判断一条线是否与四条线的碰撞/相交检查,这四条线就是矩形的四个边。

假如,我们有矩形的左边缘从(rx,ry)开始并向下延伸到ry+rh。可以把它当作一条线,然后用lineLine检测: 判断是否碰撞/相交的线是l([{x,y1},{x2,y2}])

php 复制代码
const left = lineLine(1, [{x:rx,y:ry}, {x:rx,y:ry+rh}]);

来张图,更好理解

其他边也是相同的方法

php 复制代码
const left = this.lineLine(l, [{ x:r.x, y:r.y }, { x:r.x, y:r.y + r.h }]);
const right = this.lineLine(l, [{ x: r.x + r.w, y: r.y }, { x:r.x + r.w, y:r.y + r.h }]);
const top = this.lineLine(l, [{ x:r.x, y:r.y }, { x:r.x + r.w, y:r.y }]);
const bottom = this.lineLine(l, [{ x:r.x, y:r.y + r.h }, { x:r.x + r.w, y:r.y + r.h }]);

如果四条边中任何一个与直接相交,则直线与矩形相交

kotlin 复制代码
if (left || right || top || bottom) {
    return true;
}
return false;

完整代码如下:

php 复制代码
/**
 * 
 * @param {Array} l line对象/线对象 结构[{x,y},{x,y}] 元素1:起始点; 元素2:结束点;
 * @param {Object} r 矩形对象{x,y,w,h} x/y: 矩形左上角坐标; w:宽; h:高
 * @returns boolean
 */
function lineRectangle(l,r) {
    // check if the line has hit any of the rectangle's sides
    // uses the Line/Line function below
    const left = this.lineLine(l, [{ x:r.x, y:r.y }, { x:r.x, y:r.y + r.h }]);
    const right = this.lineLine(l, [{ x: r.x + r.w, y: r.y }, { x:r.x + r.w, y:r.y + r.h }]);
    const top = this.lineLine(l, [{ x:r.x, y:r.y }, { x:r.x + r.w, y:r.y }]);
    const bottom = this.lineLine(l, [{ x:r.x, y:r.y + r.h }, { x:r.x + r.w, y:r.y + r.h }]);

    // if ANY of the above are true, the line
    // has hit the rectangle
    return left || right || top || bottom;
}

主要代码

在我的demo中,当点与矩形碰撞/相交改变固定圆的颜色,可以点上面预览进去试试。这里是部分核心代码,详细代码结构解析点击这里 这里主要是渲染和交互代码,由于baseShape和cursorShape默认形状是圆,这里opt中参数需设置baseShape为rect,cursorShape为line;cursorStartPoint为cursorShape线段的起始点;还有必须配置的hitFunc函数

ini 复制代码
const init = readyInit({
	baseShape: "rect",
	cursorShape: 'line',
	cursorStartPoint: {x: 50, y:50},
	hitFunc: (e, drawOpt,{cursorStartPoint}) => {
		return hit.lineRectangle([cursorStartPoint,{ x:e.x, y:e.y}], drawOpt)
	}
})

// 图形渲染以及交互
function check(opt) {
    const ctx = utils.getCtx();
    const canvas = ctx.canvas;
    const zoom = opt.zoom || 1;
    const width = canvas.width / zoom;
    const height = canvas.height / zoom;
    const cp = { x: Math.round(width / 2), y: Math.round(height / 2) }
    ctx.scale(zoom, zoom)
    // 基础图形的绘制参数准备开始
    const radius = opt.radius || 10;
    const baseShape = opt.baseShape || 'circle'
    let drawOpt = opt.drawOpt;;
    if (baseShape === 'circle') {
        drawOpt = {...cp, r:radius}
    } else if (baseShape === 'rect') {
        const w = opt.w || 400;
        const h = opt.h || 200;
        drawOpt = {x:(width - w) / 2, y:(height - h) / 2, w, h}
    }
    // 基础图形的绘制参数准备结束

    // 渲染方法
    function render(colliding) {
        utils.cleanCanvas(ctx)
        ctx.fillStyle = '#0095d9E0';
        ctx.strokeStyle = '#0095d9E0';
        if (colliding) {
            // 碰撞时绘制效果
            if (opt.fillRectColliding) {
                // 碰撞时,改变背景图颜色(两点碰撞时使用,由于点太小,效果不明显)
                ctx.save()
                ctx.fillStyle = "#f6ad49";
                ctx.fillRect(0, 0, width, height);
                ctx.restore()
            } else {
                // 碰撞时,改变基础图形绘制颜色
                ctx.fillStyle = "#f6ad49E0";
                ctx.strokeStyle = "#f6ad49E0";
            }
        }
        // 相交的辅助点绘制,不是每个demo都会有
        const hitPoints = hit.hitPoints;
        if (hitPoints) {
            ctx.save()
            ctx.fillStyle = "red";
            hitPoints.forEach(p => {
                drawUtils.circle(ctx, { x: p.x, y: p.y, r: 16 })
            });
            ctx.restore()
        }
        
        ctx.lineWidth = 20;
        ctx.lineJoin = "round";
        ctx.lineCap = "round";
        // 基础图形绘制
        const drawFunc = drawUtils[baseShape];
        if (drawFunc) {
            drawFunc(ctx,drawOpt)
        }
        delete hit.hitPoints;
    }
    const radius1 = opt.radius1 || 10;
    const cursorShape = opt.cursorShape || 'circle'
    canvas.addEventListener('mousemove', (e) => {
        // 调用每个demo配置的hitFunc,检测碰撞结果
        const colliding = opt.hitFunc ? opt.hitFunc(e, drawOpt, opt) : false;
        // 移动鼠标重绘
        render(colliding);

        // 绘制鼠标图形,也就是移动的图形
        ctx.fillStyle = '#6a6868E0';
        if (cursorShape === 'rect') { 
            const w = opt.cursorW || 20;
            const h = opt.cursorH || 20;
            drawUtils.rect(ctx, { x:e.x / zoom - w/2, y:e.y / zoom - h/2, w, h })
        } else if (cursorShape === 'line') {
            ctx.strokeStyle = "#6a6868E0";
            ctx.lineWidth = 20;
            ctx.lineJoin = "round";
            ctx.lineCap = "round";
            drawUtils.line(ctx, [opt.cursorStartPoint,{ x:e.x, y:e.y}])
        } else if (cursorShape === 'polygon') {
            const { x, y } = e;
            const points = [
                { x: x - 20, y: y - 20 },
                { x: x + 40, y: y - 10 },
                { x: x + 60, y: y + 20 },
                { x: x - 20, y: y + 20 },
                {x: x - 40, y: y},
            ]
            drawUtils.polygon(ctx, points)
        } else {
            drawUtils.circle(ctx, { x:e.x / zoom, y:e.y / zoom, r:radius1 })
        }
        
    })
    render();
}

代码下载

以上代码只是主要代码并不是完整代码,由于完整代码较多就不贴出来了,有需要可以点击这里,这是GitHub的代码库,详细代码结构解析点击这里

相关推荐
漠河愁22 天前
pdf文件渲染到canvas
canvas·pdf.js·fabirc.js
xachary1 个月前
前端使用 Konva 实现可视化设计器(21)- 绘制图形(椭圆)
canvas·konva
charon87781 个月前
计算机图形学 | 动画模拟
计算机图形学·unreal engine·技术美术
李伟_Li慢慢1 个月前
微分立体角与辐射度量学
前端·计算机图形学
x007xyz1 个月前
前端纯手工绘制音频波形图
前端·音视频开发·canvas
甄齐才2 个月前
canvas绘制文本时,该如何处理首行缩进、自动换行、多内容以省略号结束、竖排的呢?
canvas·html2canvas·海报·html转图片·文章分享·dom-to-image·html转image
万水千山走遍TML2 个月前
canvas绘制表格
前端·javascript·vue.js·canvas·canvas绘图·在vue中使用canvas·canvas绘制表格
xachary2 个月前
前端使用 Konva 实现可视化设计器(19)- 连接线 - 直线、折线
javascript·vue·canvas·konva
梦想身高1米82 个月前
canvas.toDataURL后图片背景变成黑色
前端·canvas
x007xyz2 个月前
Fabric.js实时播放视频并扣除绿幕
前端·javascript·canvas