Mar
13
2013

Three.js PlaneGeometry.js to Unity C#

planegeometry_unity_csharp_1

Converted this THREE.js PlaneGeometry.js (by mr.doob) to Unity c# (its similar to CreatePlane from unity wiki, but more limited)

Current version:
– Using MeshTopology.Quads
– Still some problems with the UV’s, if using more than one segments
– Also currently all the variables are as ints, so need to use even numbers
– And missing normals..

Source: ** Use the finished source from alexzzzz on comment section links instead **


using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlaneGeometry : MonoBehaviour
{
void Start()
{
CreatePlane(4,4,4,4);
}

void CreatePlane(int width, int height, int segmentsWidth, int segmentsHeight)
{
int ix, iy,
width_half = width / 2,
height_half = height / 2,
gridX = segmentsWidth,
gridY = segmentsHeight,
gridX1 = gridX + 1,
gridY1 = gridY + 1,
segment_width = width / gridX,
segment_height = height / gridY;
Vector3 normal = new Vector3( 0, 0, 1 );
List<Vector3> vertices = new List<Vector3>();
List<Vector3> vertexNormals = new List<Vector3>();
List<int> faces = new List<int>();
List<Vector2> faceVertexUvs = new List<Vector2>();
for ( iy = 0; iy < gridY1; iy++ ) {
for ( ix = 0; ix < gridX1; ix++ ) {
float x = ix * segment_width - width_half;
float y = iy * segment_height - height_half;
vertices.Add(new Vector3(x, -y, 0));
}
}

for ( iy = 0; iy < gridY; iy++ ) {
for ( ix = 0; ix < gridX; ix++ ) {
int a = ix + gridX1 * iy;
int b = ix + gridX1 * (iy + 1);
int c = (ix + 1) + gridX1 * (iy + 1);
int d = (ix + 1) + gridX1 * iy;
faces.Add(a);
faces.Add(b);
faces.Add(c);
faces.Add(d);
faceVertexUvs.Add(new Vector2(ix / gridX, iy / gridY));
faceVertexUvs.Add(new Vector2(ix / gridX, (iy + 1) / gridY));
faceVertexUvs.Add(new Vector2((ix + 1 ) / gridX, ( iy + 1 ) / gridY));
faceVertexUvs.Add(new Vector2((ix + 1 ) / gridX, iy / gridY));
}
}
// create mesh
Mesh m = GetComponent<MeshFilter>().mesh;
m.vertices = vertices.ToArray();
m.SetIndices(faces.ToArray(), MeshTopology.Quads, 0);
m.uv = faceVertexUvs.ToArray();
}
}


22 Comments + Add Comment

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.