What does this unit3d C # code mean?

Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 newDotPosition =
    mouseRay.origin - mouseRay.direction / mouseRay.direction.y * mouseRay.origin.y;

I see that newDotPosition is the position of the game object on Terrain. But what does the following code do?

mouseRay.direction / mouseRay.direction.y * mouseRay.origin.y
+4
source share
1 answer

In fact, this is some kind of basic geometry.

mouseRay.origin- camera position. Thus, mouseRay.origin.yis the height of the camera.

The result mouseRay.direction / mouseRay.direction.y * mouseRay.origin.yis the red vector in the image below. It just scales mouseRay.directionall the way across the earth.

Then he does mouseRay.origin - resultto get the point of impact on the earth in world coordinates.

enter image description here

And here is the code to see the result, if anyone is interested.

public class Test : MonoBehaviour
{
    public float originGizmoRadius = 1f;
    public float newDotPositionGizmoSize = 0.5f;
    public float directionLength = 2f;

    Vector3 origin;
    Vector3 direction;
    Vector3 newDotPosition;

    void Update()
    {
        Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        origin = mouseRay.origin;
        direction = mouseRay.direction;

        newDotPosition = origin - direction / direction.y * origin.y;
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(origin, originGizmoRadius);
        Gizmos.DrawLine(origin, origin + (direction.normalized * directionLength));

        Gizmos.color = Color.green;
        Gizmos.DrawCube(newDotPosition, newDotPositionGizmoSize * Vector3.one);
    }
}
+3
source

Source: https://habr.com/ru/post/1584717/


All Articles