Questions in topic: "triangulation"
http://answers.unity.com/questions/topics/single/295273.html
The latest questions for the topic "triangulation"procedural mesh error in triangulation
http://answers.unity.com/questions/1633637/procedural-mesh-error-in-triangulation.html
Hello! I am generating a procedural system, in question everything is fine, but I find a mathematical error in the triangulation, and I can not find the solution, maybe someone with a better eye and understanding can help me ...
according to the triangulation int list, it should be like this: 0,1,3 - 3,2,0 | 2,3,5 - 5,2,2 | 4.5.1 - 1.0.4. but the error is in the last row, I do not understand why it remains (4,5,7 - 7,6,4.). I attach an image.
![alt text][1]
I do not understand why it happens to 7, when it should be 1, and to 6 when it should be 0.
somebody help me?
public GameObject node;
public Material mat;
[HideInInspector]
public GameObject pointDown;
[HideInInspector]
public GameObject pointUp;
[HideInInspector]
public GameObject pointUpPos;
public GameObject[] pointsDown;
public Vector3[] vertex;
[Range(1,20)]
public float Height=3;
public int point;
public int[] triangles;
private int p1;
private int p2;
private int p3;
private int b;
private int p0;
private float LastComparator;
Ray ray;
RaycastHit hit;
public Mesh mesh;
public MeshFilter mf;
public MeshRenderer meshrend;
vertexEditor vertexEdit;
private int x;
public int n;
public float textureScale;
public bool Create=false;
public int change;
void Start () {
Height = 3;
mat = Resources.Load ("fence", typeof (Material)) as Material;
mat.mainTextureScale = new Vector2(1,1);
mesh = new Mesh ();
meshrend = this.gameObject.AddComponent<MeshRenderer> ();
meshrend.material = mat;
mf = this.gameObject.AddComponent<MeshFilter> ();
textureScale=1;
}
public void GenMesh(){
b = -4;
p1 = b + 2;
p2 = p1 + 1;
p3 = p2 + 2;
p0 = -1;
for (n = 0; n < triangles.Length; n+=change) {
b = x - 2;
p1 += 2;
p2 += 2;
p3 += 2;
triangles [n] = p1;
triangles [n + 1] = p2;
triangles [n + 2] = p3;
triangles [n + 3] = p3;
triangles [n + 4] = p3 - 1;
triangles [n + 5] = p1;
triangles [n + 6] = p3-1;
triangles [n + 7] = p3;
triangles [n + 8] = 1;
triangles [n + 9] = 1;
triangles [n + 10] = p0 +1;
triangles [n + 11] = p3-1;
mesh.triangles = triangles;
}
}
void Update () {
mesh.Clear ();
mesh.vertices = vertex;
mf.mesh = mesh;
point = pointsDown.Length;
pointsDown = GameObject.FindGameObjectsWithTag ("vertex");
vertex = new Vector3[pointsDown.Length];
for (x = 0; x < pointsDown.Length; x++) {
vertex[x] = new Vector3(pointsDown[x].transform.position.x,pointsDown[x].transform.position.y,pointsDown[x].transform.position.z);
}
if (point > 0) {
change = 3;
triangles = new int[pointsDown.Length/2*3];
}
if (point > 4) {
triangles = new int[pointsDown.Length *3];
change = 6;
GenMesh ();
}
// uvmap area.
Vector2[] uvs = new Vector2[vertex.Length];
for (int i = 0; i < vertex.Length; i++)
{
Vector3 uvpos = new Vector3(vertex[i].x, ((vertex[i].x) + (vertex[i].z)), vertex[i].z);
Vector3 direction = uvpos / uvpos.magnitude;
uvs[i] = new Vector2(((vertex[i].x * direction.x) + (vertex[i].z * direction.z)) / 1, vertex[i].y / 1);
}
mesh.uv = uvs;
}
}errorprocedural meshtriangulationTue, 21 May 2019 16:23:04 GMTgonzalitosk8How to sort and triangulate those Vonoroi edges?
http://answers.unity.com/questions/1544570/how-to-sort-and-triangulate-those-vonoroi-edges.html
I used this awesome [Voronoi library][1] by @jceipek but i ran into a problem and it's that i don't know how to sort edges and make the polygons
----------
![alt text][2]
----------
As you can see in this image i instantiated some cubes as the edges(see library) to see if they were sorted.
----------
The idea is that i would like to turn those edges into a polygon as seen below.
----------
![alt text][3]
[1]: https://github.com/jceipek/Unity-delaunay
[2]: /storage/temp/123110-sin-titulo.jpg
[3]: /storage/temp/123111-sin-titulo.jpgmeshmapprocedural-generationedgestriangulationTue, 21 Aug 2018 10:02:25 GMTWhiteGlovehow would i convert a drawing into a sequence of points then use Delaunay triangulation to make a crafting system and a character creation system?
http://answers.unity.com/questions/1543161/how-would-i-convert-a-drawing-into-a-sequence-of-p.html
Can someone please tell me how i'd go about converting a drawing into a sequence of points and then using Delaunay triangulation to make a crafting system and a character creation system and what that would look like in code? any help would be appreciated. thank you...conversioncraftingtriangulationcharactercustomizationFri, 17 Aug 2018 03:25:42 GMTtheweegee103Texture issue on subdivided+triangulated mesh
http://answers.unity.com/questions/1516956/texture-issue-on-subdividedtriangulated-mesh.html
Hello guys! First of all, sorry my bad english, is my first time here.
I have a project in Unity with a retro psx shader that works better with subdivided triangulated meshes. I make a plane with a subdivision and a triangularization in Blender, however when applying any texture in Unity I get only a single color texture instead my floor texture. Someone can help me?textureplanetriangulationsubdivisionMon, 11 Jun 2018 15:36:56 GMTsmile044Creating mesh from random points
http://answers.unity.com/questions/1503113/creating-mesh-from-random-points.html
Hi! I'm trying to create a 3d mesh from a random series on points.
Since this is a 3d case i think triangulator will not the best choiche for me. what can i do?
I just need a simple mesh without any particular request.![alt text][1]
Thank you!
[1]: /storage/temp/116379-untitled.pngmesh3dgenerationpointstriangulationMon, 07 May 2018 16:15:00 GMTCorvostudioHow to use Vector2.Lerp in two arrays
http://answers.unity.com/questions/1498095/how-to-use-vector2lerp-in-two-arrays.html
My question is mostly in the title. I’m stuck because I want to lerp the whole Vector2 a with the entire Vector2 b. Sorry for my english, hope you guys will understand !
Vector2[] vertices2D1 = new Vector2[] {
new Vector2(0,0),
new Vector2(54.7f,53.9f),
new Vector2(77.3f,141.8f),
new Vector2(77.3f,327.6f),
new Vector2(54.7f,428.1f),
new Vector2(0,500),
};
For example I can change the first element of my first array with vertices2D [0].x = 10f; vertices2D [0].y = 15f; but it becomes instantly (no transition), how use this with void update .And i can't use lerp with this syntax for example Vector2.Lerp(vertices2D [0].x, "here my new vector" ,0.3f);
Thank youarraylerpvector2polygontriangulationTue, 24 Apr 2018 13:56:41 GMTEarthwormsWhat polygonization algorithm does unity use for PolygonCollider2D?
http://answers.unity.com/questions/1495582/what-polygonization-algorithm-does-unity-use-for-p.html
It doesn't seem to be bayazit (which farseer uses) because they produce different results.
Wish the source code were available to seepolygoncollider2dtriangulationWed, 18 Apr 2018 12:28:59 GMTJovssen3D Meshes: how to minimize error during reduction of order?
http://answers.unity.com/questions/1472581/3d-mesh-triangulation-problem.html
a set of vertices defined by the following code:
int xMax; // this is the size of the mesh in the x dimension
int zMax; // this is the size of the mesh in the z dimension
Vector3[] vertices = new Vector3[xMax * zMax];
int i;
for (int z = 0; z < zMax; z++){
for (int x = 0; x < xMax; x++){
i = z + zMax * x; // this is just the index in the vertices array
vertices[i] = new Vector3(x, f(x,y), y); // f(x,y) might perhaps return a value from a heightmap
}
}
how do i find a subset with n of these vertices and then triangulate it in such a way that either the standard deviation of the area of the triangles is minimal, or the three-dimensional correlation coefficient is as close to 1 as possible? (preferably the latter) EDIT: any way that keeps as much detail as possible is fine
This is an extremely challenging problem and any help would be appreciated.optimizationmesheslow polytriangulationFri, 23 Feb 2018 19:32:49 GMTbekaertrubenNatural looking procedural triangular tiled 3D environment, how is it done?
http://answers.unity.com/questions/1445466/natural-looking-procedural-hexagon-tiled-environme.html
----------
**I'm trying to achieve something similar to this in my game:**
----------
http://oskarstalberg.com/game/planet/planet.html
----------
**Here's the post I've found with the most information on the creator's techniques:**
----------
http://polycount.com/discussion/163125/polygonal-planet-project-a-unity-demo-for-your-browser/p1
----------
I'm just wondering how I might go about this, LOGICALLY, what kind of techniques and methods are required here?
If you answer well, other users will forever consider you a hero!
----------
Warm regards,
Simon.procedural meshtriangulationFri, 22 Dec 2017 01:33:57 GMTmrlemonyfreshDelaunay Triangulation Help
http://answers.unity.com/questions/1417587/delaunay-triangulation-help.html
Hello folks.
I am trying to understand the process of Delaunay Triangulation more. From the research I've done, I have mostly just found posts pointing to other code bases that do it along with a lot of other stuff like Voronoi's Diagram. I would much rather try to learn from a tutorial or pseudo code then trying to dig through someone else's finished code and decipher out the little bit that I need to learn.
With that said, do you know any tutorials on how to triangulate a random set of points using this methode?
Thanks in advance!c#triangulationSun, 08 Oct 2017 06:00:55 GMTHunterAugustmy invertion of mesh.triangles is not working correctly, any idea why?
http://answers.unity.com/questions/1363808/my-invertion-of-meshtriangles-is-not-working-corre.html
Hi all,
i tried to build a mesh without back culling, to have a closed area of triangles without holes.
So in the first step i created a mesh, saved it, fliped the mesh and saved the new mesh again. The code for this process is at the end of this post.
Both Mesh.triangles are looking good, so the rotation of the triangles was successfull:
First three entries of mesh.triangle
0|1|2- 0|1|25766 - 0|24116|25766
First three entries of mesh.triangle reversed
2|1|0 - 25766|1|0 - 25766|24116|0
Now my problem is:
When i display both meshes, they looked identical.
![alt text][1]
I excpected to have a overlay of both meshes, so that i can look from the "bottom" or the "top" without any holes.
Even when i just display one of the meshes, they look identical.
i would be very happy if somenone can show me my error, or give me hint to solve this problem.
GameObject triangleMesh = new GameObject("Triangle");
triangleMesh .AddComponent<MeshFilter>();
triangleMesh .AddComponent<MeshRenderer>();
triangleMesh .GetComponent<Renderer>().material = matVertex;
***// Within the Method createMesh() a txt file will be read for the triangle construction***
triangleMesh .GetComponent<MeshFilter>().mesh = createMesh();
***// Save the Mesh as Asset***
UnityEditor.AssetDatabase.CreateAsset(triangleMesh .GetComponent<MeshFilter>().mesh, "Assets/Resources/TriangleMeshes/" + group + ".asset");
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
------------------------------------
Now for the reversion
------------------------------------
***// Like the original Mesh***
GameObject triangleMeshReverse= new GameObject("TriangleRev");
triangleMeshReverse.AddComponent<MeshFilter>();
triangleMeshReverse.AddComponent<MeshRenderer>();
triangleMeshReverse.GetComponent<Renderer>().material = matVertex;
***// Instead of reading a txt i tried to copy and flip the original mesh***
Mesh reverseMesh = triangleMesh .GetComponent<MeshFilter>().mesh;
***// Switching the rotation of the triangles***
var triangles = reverseMesh.triangles;
for (var i = 0; i < triangles3.Length; i = i + 3)
{
var tmp = triangles[i];
triangles[i] = triangles[i + 2];
triangles[i + 2] = tmp;
}
reverseMesh.triangles = triangles;
***// Save the Mesh as Asset***
UnityEditor.AssetDatabase.CreateAsset(triangleMeshReverse .GetComponent<MeshFilter>().mesh, "Assets/Resources/TriangleMeshes/" + group + "_rev" + ".asset");
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
[1]: /storage/temp/95704-mesh.pngcullingmeshestriangulationMon, 12 Jun 2017 08:58:59 GMTVorterianftl-like map generator
http://answers.unity.com/questions/1334811/ftl-like-map-generator.html
Hey guys. i am trying to do ftl-like map generator. I can generate nodes randomly and define start-exit as you can see in image. But i couldn't establish meaningful paths. I try to chose closest nodes to move, but dead end occurs. (cannot even reach exit.) I try to make circle, but not as required again. Can you suggest me a way? I want to create ftl-like movement. Thanks.
![alt text][1]
[1]: /storage/temp/91235-map.jpgpathfindinggraphmap makingtriangulationTue, 04 Apr 2017 05:02:47 GMTlie_coffin2d custom mesh triangulator problem
http://answers.unity.com/questions/1331336/2d-custom-mesh-triangulator-problem.html
Hello i having some trouble with well known triangulator class.I implemented the triangulator class directly without an edit.My aim is to create a volumetric light depending on the direction but im having this issue relative with triangles appearently.
![alt text][1]
Another view
![alt text][2]
i keep the positions of the red colored rays start&end locations and i put these locations as vertices in MESH FILTER component.
public void buildSingleVolume()
{
Mesh _mesh = new Mesh ();
_mesh.name = "VolumeMesh";
for (int i = 0; i < _vert2d.Length; i++)
{
_vert3d [i] = new Vector3 (_vert2d[i].x,_vert2d[i].y,0);
}
Triangulator _tr = new Triangulator (_vert2d);
int[] indices = _tr.Triangulate ();
_mesh.vertices = _vert3d;
_mesh.triangles =indices;
_mesh.RecalculateNormals ();
_mesh.RecalculateBounds ();
GameObject _instance = Instantiate (volume, Vector2.zero,new Quaternion(0,0,0,0)) as GameObject;
_instance.tag = "VolumeL";
_instance.GetComponent<MeshFilter> ().mesh = _mesh;
}
the mesh would show up with exact positions of red rays but it has many zig-zag or false structure.
[1]: /storage/temp/90695-display1.png
[2]: /storage/temp/90696-display2.png2dmeshtrianglesmeshfiltertriangulationTue, 28 Mar 2017 10:58:29 GMTalph1Triangulating a 2D polygon with only hull vertices.
http://answers.unity.com/questions/1323845/triangulating-a-2d-polygon-with-only-hull-vertices.html
I'm building a random road network where each node is an intersection that connects to some roads. Each road is a straight line between two intersections. Each road builds its mesh by creating 4 vertices then extruding them in the y direction using Unity's [Procedural Examples][1] project (MeshExtrusion.cs).
I want to generate my intersections in a similar manner. For each road that's built, it gives 2 of those vertices to each connecting intersection for it to store in an internal vertex list. That builds my vertex list for the intersection. All that's left is to triangulate and extrude it. However, none of my triangulation methods have worked. I've tried using the oft recommended [Triangulator.cs][2] script, which doesn't produce correct triangles for even a simple case of 4 vertices placed at each corner.
![alt text][3]
So I figured this wasn't too big a deal, since my roads are all connecting to the outside of the intersection, I really just needed a convex hull triangulation algorithm, so I came up with one:
> -Initialize a list T to hold triangle indices
> -Pick a random vertex V (or use some heuristic, I'm using the vertex with the smallest x+y term)
>
> -Sort the rest of the vertices based on the angle between Vector3.right and the line segment
> V->vertex, put this sorted list into a stack S, pushing the largest angled vertex first.
>
> -Let P be the first popped vertex from S.
>
> -While S is not empty:
>
> append V to T,
>
> append P to T,
>
> append S.Peek() to T
>
> pop the next vertex from S and set P to it.
Since my vertices are actually structs that hold the vertex position as well as the index, I can just iterate over T and collect the triangle indices to set for the triangle. The problem is, I'm getting weird results. Here are the top and bottom views of using this algorithm with one vertex on each corner and an extra one at (0.2, 0, 1.1)
![alt text][4]
I can't seem to get the triangulation correct for an arbitrary polygon.
Here is what I came up with:
[RequireComponent(typeof(MeshFilter))]
public class PolygonTriangulator : MonoBehaviour {
private void Start()
{
Vector3[] verts = new Vector3[] {
new Vector3(0.2f, 0, 1.1f),
new Vector3(-1, 0, -1),
new Vector3(-1, 0, 1),
new Vector3(1, 0, -1),
new Vector3(1, 0, 1),
};
Build(verts);
}
public void Build(Vector3[] vertices) {
Vector2[] vs = vertices.Select(v=>new Vector2(v.x, v.z)).ToArray();
vs.SortBy(v=>Vector2.right.AngleTo(v));
Mesh m = new Mesh();
m.Clear();
m.vertices = vertices;
m.triangles = SimpleTriangulator.Triangulate(vs);
//m.triangles = new Triangulator(vs).Triangulate();
m.RecalculateNormals();
m.RecalculateBounds();
GetComponent<MeshFilter>().mesh = m;
}
public static float AngleTo(this Vector2 this_, Vector2 to) {
Vector2 direction = to - this_;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
if (angle < 0f) angle += 360f;
return angle;
}
}
And here's the triangulation code:
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public struct VertexWithIndex {
public Vector2 vertex;
public int index;
public VertexWithIndex(Vector2 vertex, int index) {
this.vertex = vertex;
this.index = index;
}
public bool Is(VertexWithIndex other) {
if (other.vertex == this.vertex && other.index == this.index) {
return true;
}
return false;
}
}
public static class SimpleTriangulator {
public static int[] Triangulate(Vector2[] inputVerts)
{
if (inputVerts.Length < 3) {
if (inputVerts.Length == 2) {
return new int[] { 0, 1, };
}
return null;
}
List<VertexWithIndex> vertices = new List<VertexWithIndex>();
for (int i = 0; i < inputVerts.Length; i++)
{
vertices.Add(new VertexWithIndex(inputVerts[i], i));
}
List<int> tris = new List<int>();
// Get the vertex closest to the 4th quadrant
VertexWithIndex randomSelected = vertices.OrderBy(a=>a.vertex.x + a.vertex.y).First();
List<VertexWithIndex> restOfVertices = vertices.Where(v=>!v.Is(randomSelected)).ToList();
Stack<VertexWithIndex> V = new Stack<VertexWithIndex>(restOfVertices);
VertexWithIndex secondVertexInTriangle = V.Pop();
while (V.Count > 0) {
int[] newTriangle = EnsureCorrectOrdering(randomSelected, secondVertexInTriangle, V.Peek());
/*new int[3];
newTriangle[0] = randomSelected.index;
newTriangle[1] = secondVertexInTriangle.index;
newTriangle[2] = V.Peek().index;*/
tris.AddRange(newTriangle);
secondVertexInTriangle = V.Pop();
}
return tris.ToArray();
}
// Given three vertices, return their indices in clockwise order
static int[] EnsureCorrectOrdering(VertexWithIndex[] triangle) {
return EnsureCorrectOrdering(triangle[0], triangle[1], triangle[2]);
}
static int[] EnsureCorrectOrdering(VertexWithIndex a, VertexWithIndex b, VertexWithIndex c) {
int[] indices = new int[3];
Vector3 AC = c.vertex - a.vertex;
AC = new Vector3(AC.x, AC.z, AC.y);
Vector3 AB = b.vertex - a.vertex;
AB = new Vector3(AB.x, AB.z, AB.y);
if (Vector3.Cross(AC, AB).sqrMagnitude > 0) {
indices[0] = a.index;
indices[1] = b.index;
indices[2] = c.index;
} else {
indices[0] = a.index;
indices[1] = c.index;
indices[2] = b.index;
}
return indices;
}
}
I know I'm missing something here, since the Triangulation.cs script didn't work I think there's something wrong with my logic, code, or both. But I've been unable to fix this.
[1]: https://www.assetstore.unity3d.com/en/#!/content/5141
[2]: http://wiki.unity3d.com/index.php?title=Triangulator#C.23-_Triangulator.cs
[3]: /storage/temp/89635-tncl8nf.png
[4]: /storage/temp/89640-topbot5verts.pngmeshproceduralprocedural meshtrianglestriangulationThu, 09 Mar 2017 20:12:57 GMTGregoryNealTriangulating mesh from collider points
http://answers.unity.com/questions/1321507/triangulating-mesh-from-collider-points.html
Hi,
I've been writing a script to copy a section of any 2D collider with a circle collider. Basically, the player can draw a circle on the screen and it will copy whatever is inside of that circle and nothing that is outside it. I get collider points from the circle collider by looping through 360 degrees of the circumference of the circle.
![alt text][1]
Here is a quick summary of how it works:
- Get the 2D Collider the circle is triggered by.
- Get the collider type (Circle, polygon, box)
- Loop through the points of the collider clockwise and add them to a list
- Loop through the points in the collider and see which ones are inside the circle
- Loop through the points in the original circle collider and see which ones are contained in the other shapes collider
- Add both lists of points together
- Use the [triangulation script][2] to get a shape from the points.
I will get the shape I want some of the time, but it is often formed wrong.
![alt text][3]
The Left shape is an attempt to copy the left end of a box collider and the right shape is a copy of the right side of the same box collider. It seems to be consistent that this will be the issue depending on which side of the box I copy from.
Getting the intersection between two circle colliders always works, but box colliders and polygon colliders give me trouble.
Some steps I have tried:
- Reversing the order of the box collider (this makes it worse)
- Adding the circle colliders points before the triggered colliders points (this doesn't affect anything)
- Reversing the order of the circle collider (makes things worse)
- Decreasing the number of points for a circle collider (no change)
- Using mesh.Optimize() (do not see any changes)
Any Ideas on how to make this more robust? I thought of using the delauny triangulation, but I don't need any complex shapes and would like to keep this running fast.
Here is my current script:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
public class CopyCircle : MonoBehaviour {
Vector2 startPoint;
Vector2 endPoint;
float diameter;
MeshRenderer meshRenderer;
List<GameObject> collidedObjects;
GameObject copy;
CircleCollider2D circleCollider;
public int degreesToScan = 360; // Set to how accurate collisions should be saved.
public float percentageToCircle = .80f;
void Awake ()
{
meshRenderer = GetComponent<MeshRenderer>();
meshRenderer.enabled = false;
circleCollider = GetComponent<CircleCollider2D>();
collidedObjects = new List<GameObject>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(1))
{
startPoint = GetMousePosition();
}
else if (Input.GetMouseButton(1)) // If left click is down
{
endPoint = GetMousePosition();
Debug.DrawLine(startPoint, endPoint);
transform.position = new Vector3((startPoint.x + endPoint.x) / 2, (startPoint.y + endPoint.y) / 2, -1);
diameter = Vector2.Distance(startPoint, endPoint);
transform.localScale = new Vector2(diameter, diameter);
meshRenderer.enabled = true;
}
else if (Input.GetMouseButtonUp(1)) // Released
{
meshRenderer.enabled = false;
}
else if (Input.GetMouseButtonDown(0) && collidedObjects.Count > 0) // Left mouse down
{
if (copy)
Destroy(copy);
copy = Copy();
}
else if (Input.GetMouseButton(0) && copy)
{
copy.transform.position = GetMousePosition();
}
else if (Input.GetMouseButtonUp(0) && copy)
{
for (int i = 0; i < copy.transform.childCount; i++)
{
for (int o = 0; o < collidedObjects.Count; o++)
{
if (o != i &&
copy.transform.GetChild(o).GetComponent<Collider2D>().IsTouching(copy.transform.GetChild(i).GetComponent<Collider2D>()) &&
(!collidedObjects[o].GetComponent<Rigidbody2D>() || !collidedObjects[i].GetComponent<Rigidbody2D>()))
{
// connect the objects
copy.transform.GetChild(o).gameObject.AddComponent<FixedJoint2D>().connectedBody = copy.transform.GetChild(i).gameObject.GetComponent<Rigidbody2D>();
}
}
copy.transform.GetComponentsInChildren<Rigidbody2D>()[i].isKinematic = false;
copy.transform.GetComponentsInChildren<Collider2D>()[i].isTrigger = false;
}
}
}
Vector2 GetMousePosition()
{
return Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
void OnTriggerStay2D(Collider2D col)
{
if (meshRenderer.enabled && col.gameObject.tag != "Copy" && !collidedObjects.Contains(col.gameObject))
{
collidedObjects.Add(col.gameObject);
}
}
void OnTriggerExit2D(Collider2D col)
{
if(collidedObjects.Contains(col.gameObject))
{
collidedObjects.Remove(col.gameObject);
}
}
GameObject Copy()
{
GameObject copy = new GameObject("New Copy");
// Do the hard stuff here
// First loop through the other objects collider to see which points are inside the copy circle
for (int o = 0; o < collidedObjects.Count; o++)
{
List<Vector2> OthersColliderPoints = new List<Vector2>();
GameObject collidedObject = collidedObjects[o];
if (collidedObject.GetComponent<BoxCollider2D>()) // Box
OthersColliderPoints.AddRange(GetBoxColliderEdges(collidedObject.GetComponent<BoxCollider2D>()));
else if (collidedObject.GetComponent<PolygonCollider2D>()) // Polygon
OthersColliderPoints.AddRange(GetPolygonColliderPoints(collidedObject.GetComponent<PolygonCollider2D>()));
else // Circle
OthersColliderPoints.AddRange(GetCircleColliderPoints(collidedObject.GetComponent<CircleCollider2D>(), circleCollider, degreesToScan));
List<Vector2> PointsToAdd = new List<Vector2>();
// Loop through the other shapes points and add the ones that are inside the bounds of the circle
for (var p = 0; p < OthersColliderPoints.Count; p++)
{
if (circleCollider.OverlapPoint(OthersColliderPoints[p]))
{
PointsToAdd.Add(OthersColliderPoints[p]);
Debug.Log(OthersColliderPoints[p]);
}
}
List<Vector2> CirclesColliderPoints = new List<Vector2>();
CirclesColliderPoints.AddRange(GetCircleColliderPoints(circleCollider, collidedObjects[o].GetComponent<Collider2D>(), degreesToScan));
bool isMostlyCircle = CirclesColliderPoints.Count / degreesToScan >= percentageToCircle;
PointsToAdd.AddRange(CirclesColliderPoints);
for (int i = 0; i < PointsToAdd.Count; i++)
{
PointsToAdd[i] -= new Vector2(transform.position.x, transform.position.y); // center the points to the object
}
Vector2[] booleanShape = new HashSet<Vector2>(PointsToAdd).ToArray();
for (int i = 0; i < booleanShape.Length; i++)
{
Debug.Log(booleanShape[i]);
}
Mesh msh = CreateMeshFromPoints(booleanShape);
GameObject subCopy = new GameObject();
// Add required components to the copy object
subCopy.AddComponent<MeshRenderer>().material = collidedObjects[o].GetComponent<MeshRenderer>().material;
subCopy.AddComponent<MeshFilter>().mesh = msh;
subCopy.AddComponent<Rigidbody2D>().isKinematic = true;
subCopy.GetComponent<Rigidbody2D>().useAutoMass = true;
if (isMostlyCircle)
subCopy.AddComponent<CircleCollider2D>();
else
subCopy.AddComponent<PolygonCollider2D>().points = booleanShape;
subCopy.GetComponent<Collider2D>().isTrigger = true;
subCopy.transform.SetParent(copy.transform);
subCopy.layer = LayerMask.NameToLayer("Solid");
subCopy.tag = "Copy";
}
copy.layer = LayerMask.NameToLayer("Solid");
copy.tag = "Copy";
return copy;
}
public static Vector2 PointOnCircle(float radius, float angleInDegrees, Vector2 origin)
{
// Convert from degrees to radians via multiplication by PI/180
float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.x;
float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.y;
return new Vector2(x, y);
}
Vector2[] GetBoxColliderEdges(BoxCollider2D col)
{
return new Vector2[]
{
col.gameObject.transform.TransformPoint(col.offset + new Vector2(col.size.x, -col.size.y) * 0.5f),
col.gameObject.transform.TransformPoint(col.offset + new Vector2(col.size.x, col.size.y) * 0.5f),
col.gameObject.transform.TransformPoint(col.offset + new Vector2(-col.size.x, col.size.y) * 0.5f),
col.gameObject.transform.TransformPoint(col.offset + new Vector2(-col.size.x, -col.size.y) * 0.5f)
};
}
// Returns a list of points of circle that are inside of collider
List<Vector2> GetCircleColliderPoints(CircleCollider2D circleCol, Collider2D col, int degreeResolution)
{
List<Vector2> points = new List<Vector2>();
for (var d = 0; d < degreeResolution; d++)
{
float degree = (360 / degreeResolution) * d;
Vector2 pointOnCircle = PointOnCircle(circleCol.radius * circleCol.transform.lossyScale.x, degree, circleCol.transform.position);
if (col.OverlapPoint(pointOnCircle)) // If point on circle is inside other collider
points.Add(pointOnCircle);
}
return points;
}
List<Vector2> GetPolygonColliderPoints(PolygonCollider2D polyCol)
{
List<Vector2> polyPoints = new List<Vector2>();
for (int i = 0; i < polyCol.points.Length; i++)
{
polyPoints.Add(polyCol.transform.TransformPoint(polyCol.points[i]));
}
return polyPoints;
}
Mesh CreateMeshFromPoints(Vector2[] booleanShape)
{
// Use triangulator to get verticies for mesh
Triangulator triangulator = new Triangulator(booleanShape);
int[] indices = triangulator.Triangulate();
// Create Vector2 Verticies
Vector3[] verticies = new Vector3[booleanShape.Length];
for (int i = 0; i < verticies.Length; i++)
{
verticies[i] = new Vector3(booleanShape[i].x, booleanShape[i].y, 0);
}
// Create a mesh
Mesh msh = new Mesh();
msh.vertices = verticies;
msh.triangles = indices;
msh.RecalculateNormals();
msh.RecalculateBounds();
//msh.Optimize();
msh.name = "Copy";
return msh;
}
}
[1]: /storage/temp/89320-capture2.png
[2]: http://wiki.unity3d.com/index.php?title=Triangulator
[3]: /storage/temp/89321-final-shapes.pngmovementmeshcollider2dtriangulationSun, 05 Mar 2017 15:37:14 GMTturndapagehow to do a delaunay triangulation for 10 points using c#?
http://answers.unity.com/questions/1278389/how-to-do-a-delaunay-triangulation-for-10-points.html
Hi, I'm a noob ,just wanted to know how to triangulate some set of points . also I searched and found as3implementation but I was not able to make anything sensible out of it because I know only the basics of coding and know nothing about importing libraries. Can someone please show me the right way to go about it.c#unity 2dverticestriangulationWed, 30 Nov 2016 08:00:02 GMTjohn1995Triangulation only renders one triangle
http://answers.unity.com/questions/1277672/triangulation-only-renders-one-triangle.html
Hey!
I have run into a problem trying to create a convex hull mesh. My code only renders 1 triangle out of the 3 in the mesh. Anyone have any idea as to why?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DataLogger : MonoBehaviour {
List<GameObject> players;
Vector2[] playerPositions;
MeshFilter mf;
ConvexHull ch;
// Use this for initialization
void Start () {
Debug.Log("DataLogger starting...");
players = GameObject.Find("Map").GetComponent<GameController>().roles;
mf = gameObject.GetComponent<MeshFilter>();
//Get all player positions from player array and create Vector2D array from them
playerPositions = new Vector2[players.Count];
playerPositions = GetPlayerPositions(players);
Debug.Log("Players: " + players.Count);
foreach (Vector2 playerPos in playerPositions)
{
Debug.Log("Player at: " + playerPos.x + "," + playerPos.y);
}
//Make a new convex hull from the player positions
ch = new ConvexHull(playerPositions, mf);
ReverseNormals();
}
// Update is called once per frame
void Update () {
}
Vector2[] GetPlayerPositions(List<GameObject> players)
{
Vector2[] playerPositions = new Vector2[players.Count];
for (int i = 0; i < players.Count; i++)
{
playerPositions[i] = new Vector2(players[i].transform.position.x, players[i].transform.position.y);
}
return playerPositions;
}
void ReverseNormals ()
{
MeshFilter filter = GetComponent<MeshFilter>();
if (filter != null)
{
Mesh mesh = filter.mesh;
Vector3[] normals = mesh.normals;
for (int i = 0; i < normals.Length; i++)
normals[i] = -normals[i];
mesh.normals = normals;
for (int m = 0; m < mesh.subMeshCount; m++)
{
int[] triangles = mesh.GetTriangles(m);
for (int i = 0; i < triangles.Length; i += 3)
{
int temp = triangles[i + 0];
triangles[i + 0] = triangles[i + 1];
triangles[i + 1] = temp;
}
mesh.SetTriangles(triangles, m);
}
}
}
public class ConvexHull
{
public Vector3[] newVertices;
public Vector2[] playerPositions;
public int[] newTriangles;
MeshFilter meshFilter;
public ConvexHull(Vector2[] _playerPositions, MeshFilter _meshFilter)
{
//Sets the vertices of the convex hull to the size of the player position array
newVertices = new Vector3[_playerPositions.Length];
//Initialise mesh filter in constructor
meshFilter = _meshFilter;
//Triangulate between the player positions
Triangulator tr = new Triangulator(_playerPositions);
newTriangles = tr.Triangulate();
//Fill the vertices of the convex hull with Vector3 points made from player positions
for (int i = 0; i < newVertices.Length; i++)
{
newVertices[i] = new Vector3(_playerPositions[i].x, _playerPositions[i].y, -2.0f);
}
//Create a new mesh and set its vertices and triangles
Mesh mesh = new Mesh();
mesh.vertices = newVertices;
mesh.triangles = newTriangles;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
mesh.name = "Convex Hull";
//Sets the meshfilter's mesh to the newly created mesh
meshFilter.mesh = mesh;
}
}
}convextriangulationMon, 28 Nov 2016 21:38:11 GMTDrMowinckelhow to join random points with lines and detect intersection ? I'm looking to create a game like untangle.
http://answers.unity.com/questions/1270461/how-to-join-random-points-with-lines-im-looking-to.html
I'm a beginner and didn't find anything helpful on the internet that I understood. But I got a few leads
*I have to create random points
*perform a triangulation to form a planar graph
*randomize the vertices to make it non planar
*let the user rearrange the vertices
*detect when they are planar again
It would be very helpful if some one provided a simplified explanation for my problem.verticeslinestriangulationSat, 12 Nov 2016 14:26:22 GMTjohn1995Triangulation for Unity Mesh from Edges
http://answers.unity.com/questions/1248369/triangulation-for-unity-mesh-from-edges.html
I would like to create a mesh from a Delaunay triangulation. The Delaunay Triangulation was created using the Unity Delaunay library, and returns a list of edges. As a result, I have a list of Vector3s for the vertices and a list of edges. Each edge just contains 2 Vector3s as vertices. From this, I need to create the triangles array on a unity mesh. In the end, I should have a complete unity mesh.
My initial idea was:
1. Start with some edge.
2. Find another edge that shares a vertex.
3. Create the triangle.
4. Repeat.
But I can't figure out how I should go about implementing this.meshfacestriangulationMon, 26 Sep 2016 16:58:09 GMTritobanProblems with UV on created mesh
http://answers.unity.com/questions/1236452/problems-with-uv-on-created-mesh.html
Hi everyone!
I am trying to make an in-game map editor that will let user create asteroid belts and asteroid fields of various shapes by specifying vertices. [(Something like that)][1]
Currently I'm using a script from [(this site)][2], it works great because I can use the same script to handle both asteroid belts and fields.
The problem emerges when trying to assign a material to the object. Both via script and when assigning it manually. It seems like the image is scaled up so drasticly that no matter how large I set the Tiling, whole object uses only one pixel of the image. (When I switch it from Cutout to Texture the whole object is either fully transparent or black, also when manipulating Offset I can get other pixels of the texture to fill whole object) I think it's because of badly assigned UV, but I can't make much sense out of script from site above.
If somebody would help me understand what I'm doing wrong or maybe point me towards other methods of creating meshes in real time with holes in them, it will be greatly appreciated.
[1]: http://i.imgur.com/MU2aRb2.png
[2]: http://luminaryapps.com/blog/triangulating-3d-polygons-in-unity/meshuv mappingcreationtriangulationTue, 30 Aug 2016 09:46:07 GMTDekarenNeed Help with 3D triangulation for Android
http://answers.unity.com/questions/1217030/need-help-with-3d-triangulation-for-android.html
I just ran into the first big problem with my current Android project.
I want to display a 3d Level that is generated from 2d data. (List of obstacles with defined corner points + a fix height stored in a json file.)
I managed to draw them onto the floor using some code I found online and the triangulation code from the wiki. Now to make them 3d I would have to move the top part (which I already have) up (that is eays :P) and then draw a border/walls around it.
The Problem is that all the triangulation code I found online is 2d only. In order to draw my walls/ borders I need a 3rd axis(up). But whenever I tried to modify my code to add 3d support Unity stopped rendering any triangles at all :(
Would be great If anyone could help me with this.
This is what I currently use:
private static Mesh CreateMesh(List<Vector3> verts)
{
var tris = new Triangulator(verts.Select(x => x.ToVector2xz()).ToArray());
var mesh = new Mesh();
var vertices = verts.Select(x => new Vector3(x.x, x.y, x.z)).ToList();
var indices = tris.Triangulate().ToList();
//var uv = new List<Vector2>();
var n = vertices.Count;
for (int index = 0; index < n; index++)
{
var v = vertices[index];
vertices.Add(new Vector3(v.x, v.y, v.z));
}
for (int i = 0; i < n - 1; i++)
{
indices.Add(i);
indices.Add(i + n);
indices.Add(i + n + 1);
indices.Add(i);
indices.Add(i + n + 1);
indices.Add(i + 1);
}
indices.Add(n - 1);
indices.Add(n);
indices.Add(0);
indices.Add(n - 1);
indices.Add(n + n - 1);
indices.Add(n);
mesh.vertices = vertices.ToArray();
mesh.triangles = indices.ToArray();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}c#android3dtriangulationSat, 16 Jul 2016 18:02:24 GMTJacky2611Filling Closed Shapes
http://answers.unity.com/questions/1146571/filling-closed-shapes.html
Hello,
I am using Vectrosity to draw some some shapes on screen run time. I also need to fill these shapes and none of them are really trivial shapes. So after doing some research I figured the best way would be to do it by creating a run-time mesh. Now this almost works for me but has a big issue.
This is my process.
1) I have defined my complex shapes as a set of 2D vertices that I extracted from Illustrator. These vertices I feed to the Vectrosity's Catmul spline function to create my shapes.
2) I then project these vertices in the real space using ScreenToWorldPoint to get 3D vertices.
3) I then pass these vertices to a program that Triangulates these points to a mesh (I use the classic Triangulate script on wiki)
4) I then clean up a little and align
Now all this works well if the camera is not rotated and the forward vector of the camera is orthogonal to the XY plane. The moment I rotate the camera the alignment of the mesh and the vector lines is completely gone.
Here is the image of the vectorline and mesh when the camera is not rotated
![alt text][1]
And here is the image when the camera is rotated
![alt text][2]
Here is the function that projects the point into 3D space
void DrawPolygon () {
Vector2[] tempVerts = new Vector2[allLinePoints.Count];
for(int i=0; i<allLinePoints.Count; i++) {
Vector3 projectedPoint = Camera.main.ScreenToWorldPoint(new Vector3(allLinePoints[i].x, allLinePoints[i].y, 10.0f));
tempVerts[i] = new Vector2(projectedPoint.x, projectedPoint.y);
}
polyTarget.SendMessage("Create", tempVerts);
}
This message is sent to a generic Triangulation script. Here it is
using UnityEngine;
using System.Collections;
using System.Linq;
public class CreatePolygon : MonoBehaviour {
public Material meshMaterial;
public void Create (Vector2[] verts) {
Triangulator tr = new Triangulator (verts);
int[] indices = tr.Triangulate ();
// Create the Vector3 vertices
Vector3[] vertices = new Vector3[verts.Length];
for (int i=0; i<vertices.Length; i++) {
vertices[i] = new Vector3(verts[i].x, verts[i].y, 0);
}
// Create the mesh
Mesh msh = new Mesh();
msh.vertices = vertices;
msh.triangles = indices;
msh.RecalculateNormals();
msh.RecalculateBounds();
// Set up game object with mesh;
gameObject.AddComponent(typeof(MeshRenderer));
MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
filter.mesh = msh;
GetComponent<Renderer> ().material = meshMaterial;
StartCoroutine (FlipNormal ());
}
public void ResetMesh (Vector2[] verts) {
Triangulator tr = new Triangulator (verts);
int[] indices = tr.Triangulate ();
// Create the Vector3 vertices
Vector3[] vertices = new Vector3[verts.Length];
for (int i=0; i<vertices.Length; i++) {
vertices[i] = new Vector3(verts[i].x, verts[i].y, 0);
}
// Create the mesh
Mesh msh = new Mesh();
msh.vertices = vertices;
msh.triangles = indices;
msh.RecalculateNormals();
msh.RecalculateBounds();
// Set up game object with mesh;
MeshFilter filter = GetComponent<MeshFilter> ();
filter.mesh = msh;
GetComponent<Renderer> ().material = meshMaterial;
StartCoroutine (FlipNormal ());
}
IEnumerator FlipNormal() {
yield return new WaitForSeconds (0.1f);
Mesh mesh = (GetComponent<MeshFilter> () as MeshFilter).mesh;
mesh.uv = mesh.uv.Select(o => new Vector2(1 - o.x, o.y)).ToArray();
mesh.triangles = mesh.triangles.Reverse().ToArray();
}
}
Now this seems to be an obvious problem to have but I am just not being able to crack it. I have a feeling the solution is some mathematics that is completely escaping me right now. Can someone please help and point me to the right direction. I need to be able to align the mesh to the outline even when the camera is rotated.
Thanks
[1]: /storage/temp/64534-1.jpg
[2]: /storage/temp/64535-2.jpgscripting problemmeshscreentoworldpointtriangulationWed, 24 Feb 2016 08:54:40 GMTromitrajTriangulation for my procedural 2D Polygon Collider is different than that of my Mesh, does anyone know why?
http://answers.unity.com/questions/1141781/triangulation-for-my-procedural-2d-polygon-collide.html
I am generating a number of terrain elements by creating a height-map for the upper and lower bounds, then passing these through a triangulation algorithm to generate the triangles which are used to generate the mesh.
The mesh is generated as follows:
Vector3[] meshVertices = new Vector3[vertices.Length];
// Convert Vector2's to Vector3
for (int i = 0; i < vertices.Length; i += 1) {
Vector2 vertex = vertices[i];
meshVertices[i] = new Vector3(vertex.x, vertex.y, transform.position.z + z);
}
// Create a new mesh and set the vertices, uv's and triangles
Mesh mesh = new Mesh();
mesh.vertices = meshVertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
// Create a new game object
GameObject go = new GameObject(texture);
After this I add the mesh renderer etc before detecting the generated element type and deciding weather to apply a polygon collider 2D.
PolygonCollider2D poly = go.AddComponent<PolygonCollider2D> () as PolygonCollider2D;
poly.points = vertices;
This is where my problem lies. For generated meshes I wish to attach a polygon collider 2D, The colliders triangulation ends up being different than that of the mesh.
BLUE = Lower terrain MESH with flat bottom, no overlaps (working)
GREEN = Lower terrain POLYGONCOLLIDER2D with flat bottom, no overlaps (working)
![alt text][1]
***And heres the problem**
Upper terrain MESH with overlapping y values for upper and lower heightmap (working):
Upper terrain POLYGONCOLLIDER2D with overlapping y values for upper and lower heightmap (broken):
![alt text][2]
I can't understand why the mesh triangles have been calculated correctly while the polygon triangles have not. My best guess is that mesh.triangles is cleaning it up for the mesh while this is not being applied to the polygon collider. Any advice on the matter is greatly appreciated!
I am happy to provide further code if needed, just didn't want to overload the question with it.
[1]: /storage/temp/63880-1.jpg
[2]: /storage/temp/63881-2.jpgproceduralprocedural meshtrianglespolygon collider 2dtriangulationMon, 15 Feb 2016 16:05:12 GMTniallmcAutomatically generating the triangle list for a mesh
http://answers.unity.com/questions/1141782/automatically-generating-the-triangle-list-for-a-m.html
Hello
Is there a way or algorithm for automatically specifying how a list of vertices should be connected?
For example lets say I have this (in 2D for simplicity):
*(0,0) *(2,0)
*(-1,-1) *(1,-1)
So I add the vertices in the order (-1,-1),(0,0),(1,-1),(2,0)
and then to the triangle list I add the indices 0,1,2 and 2,1,3 and this should generate a mesh with two triangles.
However, as the number of vertices get larger the process of defining the triangles get more tedious, unless of course I add the vertices in a sort of sorted order so that I can keep track of which triangle i'm and just add an offset each time (which I don't want to do).
Where i'm going with this is this (again in 2D for simplicity):
I want to define an array, say:
[0 , 0 , 1 , 0 , 1 , 0]
[0 , 0 , 0 , 0 , 0 , 0]
[0 , 1 , 0 , 1 , 0 , 0]
which would represent the xy-plane and points in that array are vertices (1) or contain nothing (0). And so, array[0,0] would be x=0, y=0 (nothing) and array[2,1] (a vertex) would be x=1, y=2. Using this, I'd then like to generate a mesh.
I know there's a triangulate script for 2D but that doesn't work for 3D?
Is this possible? Any help would be appreciated.
Thanksprocedural meshtrianglestriangulationMon, 15 Feb 2016 11:00:18 GMTAmposterConvex volumetric 3d object from points (vertices)
http://answers.unity.com/questions/1136270/convex-volumetric-3d-object-from-points-vertices.html
I have a many vector3 random points. How can i generate convex mesh from them?
![alt text][1]
[1]: /storage/temp/63043-pfkhv.pngmeshmeshfilterconvextriangulationMon, 01 Feb 2016 09:17:56 GMTGLeBaTiTriangulation Problems
http://answers.unity.com/questions/1084151/triangulation-problems.html
I have a collection of points. The vertex order looks like this:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
The points are lay out like a plane, and i want the final result to look like a plane. I tried using the Triangulation script on the Unify Community Wiki, but it did not work, due to having points "inside" the outer points.
Currently, my code for triangulation is this:
Vector3[] vertices = new Vector3[xMax * yMax];
int[] triangles = new int[vertices.Length * 3];
for (int x = 0; x < xMax; x++) {
for (int y = 0; y < yMax; y++) {
int v = x + (y * xMax);
// Assign the vertex position (this isnt the problem)
vertices[v] = vertexPos;
// Assign triangles (the thing that doesn't work)
// The if then statements are to make sure the indicies dont go out of bounds
if (t < triangles.Length - 5) {
if (v < vertices.Length - xMax) {
triangles[t++] = v;
triangles[t++] = v + 1;
triangles[t++] = v + xMax;
triangles[t++] = v + 1;
triangles[t++] = v + xMax;
triangles[t++] = v + xMax + 1;
}
}
}
}
All the things I've tried have not resulted in a nice smooth flat plane like i would like it to be.meshmeshestriangulationSun, 18 Oct 2015 20:03:08 GMTGameDudeMesh with Holes
http://answers.unity.com/questions/1053496/mesh-with-holes.html
Ok here is the deal.
I have a Polygon and want to create a Mesh out of it. No Problem just assign the right triangles and im good to go. Thing is I want to Create a Mesh out of several Polygons. One Polygon ist the wall the others are Openings inside this Wall. I know wich are the openings and which is the big one but nothing else.
Is there any script or algortihm that assignes the triangles correctly? Or do I need to build it from ScratchmeshtrianglestriangulationMon, 07 Sep 2015 03:48:22 GMTscylorTriangulation for complex polygons
http://answers.unity.com/questions/920770/triangulation-for-complex-polygons.html
Hello,
I`m working on a project in which i have to draw polygons from coordinates i know and then do a unity visible mesh with those(2d polygons in 3D environnement).
I read about how to create a mesh and I managed to create a simple polygon and triangulate it with a script without any problem.
My problem is, I need to do the same things but with more difficult polygons which may contain holes. I searched on the internet algorithm i may use to automate it and mostly found out ear clipping algorithm/delaunay triangulation.
Anybody ever faced this problem and have some piece of code to be started with?
Thank you very muchtriangulationTue, 10 Mar 2015 22:13:53 GMTSoulwax62clCreating a Mesh from code and applying texture
http://answers.unity.com/questions/911713/creating-a-mesh-from-code-and-applying-texture.html
I'm using this:
http://wiki.unity3d.com/index.php?title=Triangulator
To create a mesh from code. Before I call recalculate normals and bounds, I set the uv to the vertices2D so that I can apply a texture to the material.
msh.RecalculateNormals();
msh.RecalculateBounds();
msh.uv = vertices2D;
However, if I create the mesh anywhere other than zero relative to the item the script is attached to, it seems that the texture doesn't move with it. Meaning, if the mesh is created up and to the right, the texture is locked to the center and the mesh only picks up part of the texture.
What am I doing wrong? I ideally want this object to be able to create several meshes, each having the texture I'm applying.texturemeshtriangulationSat, 28 Feb 2015 15:08:46 GMTzeteginaraTerrain heightmap tessellation - how to avoid triangles folding?
http://answers.unity.com/questions/873106/terrain-heightmap-tessellation-how-to-avoid-triang.html
If you visualise a terrain heightmap as a grid of quads, the quads are triangulated along +x & +z.
e.g. the quad (0,0) (0,1) (1,1) (0,1) is cut between (0,0) and (1,1) [See below]
This means that if you set heights on a diagonal line of points with direction (1,1), you get a perfect line.
But if your line has direction (-1,1) or (1,-1) then you get a broken line of individual spikes, because the triangles fold between each point.
This isn't a problem when there is thickness/width to the area, but even then the edges will be jagged.
I know this problem isn't often seen because most ways of modifying the terrain will involve some smoothing/anti-aliasing, but when you're trying to be precise it's very obvious.
Is there any way to reduce this problem? Can the heightmap be made to tessellate in both directions?
Or will it just be a case of anti-aliasing the edges with a line algorithm?
![alt text][1]
[1]: /storage/temp/38528-terrainfolds.jpgterrainheightmaptriangulationSat, 10 Jan 2015 08:17:04 GMTSteve555