- Home /
Having an array of points(vector2), how do I create a 2d terrain? (new to unity)
I'm new to unity and i don't know what to look for to obtain what i need. So basically this what i have
The round thingie is my rigidbody with polygon collider. The lines you see are generated from an array of points and drawn with debug.SrawLine at the moment. What i need to get is this :
What "thing" do I have to do to make this and make it a rigid body? Terrain? Meshes? Polygons? It's not very clear to me how it should work even if i did my researches. Of course those lines will need to be a closed perimeter, at the least i think. But that's not a problem.
Answer by satanas · Jan 19, 2020 at 09:42 AM
Probably a little too late but it could be helpful if someone else comes across the same problem. This is how I solved it. First, make sure each of your shapes (in your case top and bottom) have attached:
A
MeshRenderer
withSprite-Default
as materialA
PolygonCollider2D
(empty)A
MeshFilter
Then create a C# script with the code below and attach it to the game object:
public class Landscape : MonoBehaviour {
private MeshFilter meshFilter;
private PolygonCollider2D polygonCollider;
void Start() {
meshFilter = GetComponent<MeshFilter>();
polygonCollider = GetComponent<PolygonCollider2D>();
// Let's assume you have a FooBar method that returns your array of points
Vector2[] myArrayOfPoints = FooBar();
// We need to convert those Vector2 into Vector3
Vector3[] vertices3D = System.Array.ConvertAll<Vector2, Vector3>(vertices2D, v => v);
// Then, we need to calculate the indices of each vertex.
// For that, you can use the Triangulator class available in:
// http://wiki.unity3d.com/index.php?title=Triangulator
Triangulator triangulator = new Triangulator(vertices2D);
int[] indices = triangulator.Triangulate();
// Now we need to create a color for each vertex. I decided to put them all white but you
// can adjust it and change it according to your needs
Color[] colors = Enumerable.Range(0, vertices3D.Length)
.Select(i => Color.white)
.ToArray();
// Finally, create a Mesh and set vertices, indices and colors
Mesh mesh = new Mesh();
mesh.vertices = vertices3D;
mesh.triangles = indices;
mesh.colors = colors;
// Recalculate the shape of the mesh
mesh.RecalculateNormals();
mesh.RecalculateBounds();
// And add the mesh to your MeshFilter
meshFilter.mesh = mesh;
// For the collisions, basically you need to add the vertices to your PolygonCollider2D
polygonCollider.points = vertices2D;
}
}
I tested it with some random generated mountains and you can see how a box is colliding with these mountains in the screenshot below:
Your answer
Follow this Question
Related Questions
Generate collision mesh from 2d texture? 0 Answers
Terrain Detail Mesh Collisions 1 Answer
Find cardinal direction of collision based on 2D Cartesian coordinates 1 Answer
Crawling around the terrain 3 Answers
Collision with Texture when alpha=1 1 Answer