Ray: finding out x and z coordinates where it intersects y = 0

Hello, I’m trying to do an RTS style building placement where the blueprint of an object follows the mouse while dragging along the ground.

The catch is that this is that I’m effectively placing the terrain, there may or may not be something in that location, so collision detection isn’t really an option.

I need a reasonably simple way to find out where my ScreenPointToRay ray intersects y=0 but my vector math is rusty to non-existant. Is there a function or set of functions in Unity that would make this simpler than breaking down the two vectors I have into individual numbers and coding a wall of geometry?

what I currently have:

void Update()
{
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));

???

temp.transform.position = new Vector3((int)???,0,(int)???);
}

You can create a horizontal logic plane at y=0, then use a Plane.Raycast to find where the ray hits the plane and get the exact position with Ray.GetPoint:

void Update(){
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  // create a plane at 0,0,0 whose normal points to +Y:
  Plane hPlane = new Plane(Vector3.up, Vector3.zero);
  // Plane.Raycast stores the distance from ray.origin to the hit point in this variable:
  float distance = 0; 
  // if the ray hits the plane...
  if (hPlane.Raycast(ray, out distance)){
    // get the hit point:
    temp.transform.position = ray.GetPoint(distance);
  }
}

If it’s really just y=0 you are interested in, make a plane with collider that covers your whole area, remove the MeshRenderer, so that it’s an invisible collider, and place it at y=0.

Then you can simply raycast at this particular collider, using Collider.Raycast(…), and it will always return the intersection with y=0 at that point.

Knowing the x1, to get the y1 and z1, simply use the direction vector v= ( x, y, z) :

dx = x1 - x;

dy = v.y * dx/v.x;

dz = v.z * dx/v.x;

y1 = y + dy;

z1 = z + dz;