- Home /
Question by
mzeman2203 · Feb 10 at 06:15 PM ·
c#vertices
Moving certain vertices to a position
I have a game where I have a mesh terrain and a building system. When you build a building and place it, I would like the mesh to fit well onto the building.
Is it possible to move the vertices of a plane (terrain), only below a cube (building).
So this-
To this-
orignal.png
(4.6 kB)
orignal2.png
(4.4 kB)
Comment
Answer by BastianUrbach · Feb 13 at 11:22 AM
For modifying meshes, see the examples in the scripting reference: Mesh. To test if a vertex is below an object and get its distance to it, you can use Collider.Raycast with an upwards ray starting at the vertex. Here is a basic example:
using UnityEngine;
public class RaiseTerrain : MonoBehaviour {
public Collider building;
void Start() {
var mesh = GetComponent<MeshFilter>().mesh;
var vertices = mesh.vertices;
for (int i = 0; i < vertices.Length; i++) {
var vertex = transform.TransformPoint(vertices[i]);
var ray = new Ray(vertex, Vector3.up);
if (building.Raycast(ray, out var hit, Mathf.Infinity)) {
vertex.y += hit.distance;
vertices[i] = transform.InverseTransformPoint(vertex);
}
}
mesh.SetVertices(vertices);
mesh.RecalculateBounds();
mesh.RecalculateNormals();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613052851im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problem Creating a 2D Mesh 1 Answer
Trouble with positions of vertices 1 Answer