Line Renderer on top of Mesh
Hi there,
I am using a Line renderer so players can draw the line for their characters to follow. The problem is that I have a procedural generated terrain as my map, which is not flat. My line will be visible as long as the terrain has low height, but as soon as the terrain gets a little higher, the line is rendered below the terrain, making it invisible. I need the line to always be on top of my mesh. Also, I don't let the player start the movement line too far away from the player and Unity seems to be calculating the distance from below the mesh, as sometimes it won't let me draw. I thought that using a Raycast and specifying the mask would be enogh but it apparently is not.
if(Input.GetButton("LeftMouse")){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,100,ground)){
if(points.Count != 0 || Vector3.Distance(player.transform.position,hit.point)<2f){
points.Add(hit.point);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPositions(points.ToArray());
}
else{
Debug.Log("Too far away");
}
}
I have not found any information regarding this problem online so I come here for help as I am new to Unity. Is there a way to fix this issue or is this a wrong approach?
Answer by DuduRamos · Mar 08, 2020 at 12:39 PM
This is a common phenomena called Z Fighting and I did two things to solve this:
I switched from a terrain mesh build with triangles to the actual Terrain gameobject that Unity has. I seems to approximate heights better.
I added .1f to any point so Z Fighting doesn't happen anymore but the line is not too far away from the terrain.
Vector3 p = hit.point;
p.y += 0.1f;