如果vector2在其他两个vector2之间则进行检测

问题描述 投票:0回答:1

正如标题所暗示的,我正在尝试不同的方法,但没有解决。我需要检查鼠标在PlayMode中是否在两个2d点之间。我考虑过使用rect快速在两个vector2之间构建一个矩形,并使用rect.contains检查鼠标的位置是否在矩形内。如果矩形是水平的,但屏幕上的点未对齐,则此方法有效,在我看来,没有办法创建斜矩形。我试图计算两点之间的distance,以创建矩形并移动其center使其旋转,但它似乎不起作用。而且似乎没有办法在屏幕上显示矩形,因此很难理解在更改某些参数后矩形是否保持其原始形状。你有什么建议吗?但是,我需要检测区域为矩形,而不是一行。使用LineCast可以解决,但检测到的区域太窄。

我想到了两个向量之间的矩形。想象一下连接两个矢量的一像素线。现在,将线条的粗细增加到10/20像素,以便在原始线条之前和之后稍稍检测到鼠标。也许我错了,但是我认为新的rect是一个很好的解决方案,但是就我看过它的所有属性而言,我不明白如何在没有太多代码行的情况下在两个向量之间构建它。

c# unity3d
1个回答
2
投票

您可以做一些向量数学运算来:

  1. 确定测试点是否不在两个点之外。

  2. 计算距您的点的线段的距离,如果等于或低于某个阈值,则认为该线段位于两点之间的线段“附近”。

  3. 如果它在该线段“附近”,而不是在两个点“之外”,则将其视为在这些点之间。

例如:

Vector3 point1 = new Vector2(10f, 10f);
Vector3 point2 = new Vector2(50f, 50f);
float closeThreshold = 5f;

Vector3 testPoint = new Vector2(20f, 21f);

Vector3 segmentDirection = (point2-point1).normalized;
Vector3 point1ToTest = testPoint - point1;
Vector3 testToPoint2 = point2 - testPoint;

// determine if testPoint is not "outside" the points
if (       Vector3.Dot(segmentDirection, point1ToTest.normalized) >= 0f
        && Vector3.Dot(segmentDirection, testToPoint2.normalized) >= 0f)
{
    Vector3 closestPointOnSegment = point1 
            + segmentDirection * Vector3.Dot(point1ToTest, segmentDirection);

    // determine if testPoint is close enough to the line segment point1->point2
    if ((closestPointOnSegment - testPoint).magnitude <= closeThreshold)
    {
        // testPoint is "between" point1 and point2
    } 
}

将与Vector3Vector2一起使用,它们将安全地转换为Vector3,如上所示。


[如果仅考虑点是否恰好位于两个位置之间,请采用从测试点到线的任一端的方向,如果这些方向之间的点积为-1,则该点在它们之间:

Vector3 point1 = new Vector2(-1f,-1f);
Vector3 point2 = new Vector2(1f,1f);

Vector3 testPoint = new Vector2(0f,0f);

Vector3 testTo1 = (point1-testPoint).normalized;
Vector3 testTo2 = (point2-testPoint).normalized;

if (Mathf.Approximately(-1f, Vector3.Dot(testTo1, testTo2)))
{
    // testPoint is between point1 and point2
}

将与Vector3Vector2一起使用,它们将如上所述安全地转换为Vector3

© www.soinside.com 2019 - 2024. All rights reserved.