如何在平面上反射物体?

时间:2019-03-18 10:18:11

标签: unity3d

给定一个平面游戏对象,我想反映一个关于该平面的对象

一个简单的例子是一个平面在0,0,0且物体在0,-1,0处不旋转,这导致在0,1,0上的反射位置

更复杂的情况是,平面在0,0,0处,在x轴上旋转45度,物体在0,-1,-1处,从而在0,1,1处产生反射位置

我正在寻找一种可以在任何位置旋转任何平面的情况下使用的解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用Plane.ClosestPointOnPlane获取飞机上的相应位置。

因此,您需要首先创建一个Plane。作为inNormal,您必须使用垂直于平面的向量。

  • 对于Quad基元,这是负forward向量
  • 对于Plane原语,它是up向量。

比起您可以简单地在原始对象和ClosestPointOnPlane之间使用Vector来移动到相同的相对位置,但Vector取反了:

public class ReflectPosition : MonoBehaviour
{
    public Transform Source;
    public Transform Plane;

    // Update is called once per frame
    private void Update()
    {
        // create a plane object representing the Plane
        var plane = new Plane(-Plane.forward, Plane.position);

        // get the closest point on the plane for the Source position
        var mirrorPoint = plane.ClosestPointOnPlane(Source.position);

        // get the position of Source relative to the mirrorPoint
        var distance = Source.position - mirrorPoint;

        // Move from the mirrorPoint the same vector but inverted
        transform.position = mirrorPoint - distance;
    }
}

结果(蓝色球已附加此组件并反映了白色球的位置)

enter image description here

答案 1 :(得分:1)

您可以像这样使用Vector3.ProjectOnPlane

//I used a cube and a quad. So i am finding the projection of cube's position onto quad
public GameObject cube;
private Vector3 point;
private Vector3 projectedPoint;
void Start () {
    point = cube.transform.position;
    planeOrigin = gameObject.transform.position;
    Vector3 v = point - planeOrigin;
    Vector3 d = Vector3.Project(v, -gameObject.transform.forward);
    projectedPoint = point - d;
}   

void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawLine(point, projectedPoint);
}

您可以从下图中看到它的工作原理:

enter image description here

然后您可以通过计算点与投影点之间的方向并将其乘以它们之间的两倍距离来计算反射,如下所示:

 Vector3 reflection = point + 2*(projectedPoint - point);