Get Mouse World Position 1

Get Mouse World Position

public Vector3 worldPosition;

void Update()
{
    Plane plane = new Plane(Vector3.up, 0);

    float distance;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (plane.Raycast(ray, out distance))
    {
        worldPosition = ray.GetPoint(distance);
    }
}Copy

Here is what the above code is Doing:
1. We create a new Plane object, which is a flat surface that extends infinitely in all directions.
2. We create a Ray object, which is a line that extends infinitely in one direction.
3. We use the ScreenPointToRay method to create a ray that starts at the camera and extends out to the mouse position.
4. We use the Raycast method to check if the ray intersects with the plane. If it does, we get the distance from the ray origin to the point of intersection.
5. We use the GetPoint method to get the world position of the point of intersection.

Similar Posts