分离轴定理在Javascript中的实现

Separation Axis Theorem implementation in Javascript

本文关键字:实现 Javascript 定理 分离      更新时间:2023-09-26

我正在尝试对两个凸形状进行简单的碰撞检测测试。我的形状定义如下

var convex2 = [
    {x:-0.1, y:-0.1},
    {x: 0.12, y:-0.07},
    {x: 0.22, y:0.0},
    {x: 0.0, y:0.2},
    {x:-0.1, y:0.12}
];
var convex = [
        {x:-0.08, y:-0.07},
        {x: 0.07, y:-0.06},
        {x: 0.09, y: 0.08},
        {x:-0.07, y: 0.09},
];

我有一个函数来检查两个多边形是否相互碰撞,并称之为

convexConvex(convex, convex2)

以下是我实现SPT 的尝试

首先,我是Javascript的初学者,所以如果我在语法方面做了错误的事情,请告诉我。

我已将投影轴定义为水平x轴(1,0)。我不确定这是否正确。

即使它们没有碰撞,函数也总是返回true。我做错了什么?

function convexConvex(p1, p2) {
    //TODO
    var axis = {x:1,y:0};
    var p2MaxValue = Number.NEGATIVE_INFINITY;
    var p2MinValue = Number.POSITIVE_INFINITY;
    var p1MaxValue = Number.NEGATIVE_INFINITY;
    var p1MinValue = Number.POSITIVE_INFINITY;
    var p2MaxPoint; //Max point for P2
    var p2MinPoint; //Min point for P2
    var p1MaxPoint; //Max point for p1
    var p1MinPoint; //Min point for p1
    //find min and max points in shape p2
    for(var i in p2)
    {
        var dotProduct = p2[i].x*axis.x + p2[i].y*axis.y;
        if(dotProduct > p2MaxValue)
        {
            p2MaxValue = dotProduct;
            p2MaxPoint = p2[i];
        }
        if(dotProduct < p2MinValue)
        {
           p2MinValue = dotProduct;
           p2MinPoint = p2[i];
        }
    }
    //find min and max points in shape p1
    for(var i in p1)
    {
        var dotProduct = p1[i].x*axis.x + p1[i].y*axis.y;
        if(dotProduct > p1MaxValue)
        {
            p1MaxValue = dotProduct;
            p1MaxPoint = p1[i];
        }
        if(dotProduct < p1MinValue)
        {
           p1MinValue = dotProduct;
           p1MinPoint = p1[i];
        }
    }
    //compare the min and max projection values
    if(p2MinValue < p1MaxValue || p2MaxValue < p1MinValue)
        return true
    return false;
}

由于p2MinValuep1MinValue都从负无穷大开始,所以它们都不会取任何其他值。不,轴不能正确。

我找到了一篇很好的文章,并在可汗学院完成了我的表演:https://www.khanacademy.org/computer-programming/polygon-collision-detector/6339295315755008