Sunday, November 10, 2019

How can I reflect a point about a line in Unity?



I am drawing a line using the line renderer in the following way:


public class MyLineRenderer : MonoBehaviour {
LineRenderer lineRenderer;

public Vector3 p0, p1;


// Use this for initialization
void Start () {
lineRenderer = gameObject.GetComponent();
lineRenderer.positionCount = 2;

lineRenderer.SetPosition(0, p0);
lineRenderer.SetPosition(1, p1);

}


}


From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?


enter image description here



Answer



// Form a unit vector in the direction of the line.
var lineDirection = (p1 - p0).normalized;

// Rotate the vector 90 degrees in the XY plane
// to get a vector perpendicular to the mirror line.
var perpendicular = new Vector3(-lineDirection.y, lineDirection.x, 0);

// If you're working in the XZ plane instead, it's
// (-lineDirection.z, 0, lineDirection.x)

// Take away a's perpendicular offset from this line, twice.
// Once to flatten a onto the line, and a second time to make b,
// an equal distance away on the opposite side of the line.
var b = a - 2 * Vector3.Dot((a - p0), perpendicular) * perpendicular;

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...