TrueSync
TSMeshCollider.cs
1 using System.Collections.Generic;
2 using System.Linq;
3 using UnityEngine;
4 
5 namespace TrueSync {
6 
10  [AddComponentMenu("TrueSync/Physics/MeshCollider", 0)]
11  public class TSMeshCollider : TSCollider {
12 
13  [SerializeField]
14  private Mesh mesh;
15 
19  public Mesh Mesh {
20  get { return mesh; }
21  set {
22  mesh = value;
23  vertices = GetVertices();
24  indices = GetIndices();
25 
26  if (_body != null) {
27  _body.Shape = CreateShape();
28  }
29  }
30  }
31 
32  private List<TSVector> vertices;
33 
37  public List<TSVector> Vertices {
38  get {
39  if (vertices == null)
40  vertices = GetVertices();
41  return vertices;
42  }
43  }
44 
45  private List<TriangleVertexIndices> indices;
46 
50  public List<TriangleVertexIndices> Indices {
51  get {
52  if (indices == null)
53  indices = GetIndices();
54  return indices;
55  }
56  }
57 
61  public void Reset() {
62  if (mesh == null) {
63  var meshFilter = GetComponent<MeshFilter>();
64  mesh = meshFilter.sharedMesh;
65  }
66  }
67 
71  public override Shape CreateShape() {
72  var octree = new Octree(Vertices, Indices);
73  return new TriangleMeshShape(octree);
74  }
75 
76  private List<TriangleVertexIndices> GetIndices() {
77  var triangles = mesh.triangles;
78  var result = new List<TriangleVertexIndices>();
79  for (int i = 0; i < triangles.Length; i += 3)
80  result.Add(new TriangleVertexIndices(triangles[i + 2], triangles[i + 1], triangles[i + 0]));
81  return result;
82  }
83 
84  private List<TSVector> GetVertices() {
85  var result = mesh.vertices.Select(p => new TSVector(p.x * lossyScale.x, p.y * lossyScale.y, p.z * lossyScale.z)).ToList();
86  return result;
87  }
88 
89  protected override Vector3 GetGizmosSize() {
90  return lossyScale.ToVector();
91  }
92 
93  protected override void DrawGizmos() {
94  Gizmos.DrawWireMesh(mesh);
95  }
96 
97  }
98 
99 }
FP y
The Y component of the vector.
Definition: TSVector.cs:39
override Shape CreateShape()
Creates a shape based on attached mesh.
Shape Shape
Shape used by a collider.
Definition: TSCollider.cs:19
Collider with a mesh shape.
List< TriangleVertexIndices > Indices
A list of mess related structs.
A vector structure.
Definition: TSVector.cs:29
void Reset()
Gets (if any) the mesh attached to this game object.
FP z
The Z component of the vector.
Definition: TSVector.cs:41
Abstract collider for 3D shapes.
Definition: TSCollider.cs:12
TSVector lossyScale
Holds an first value of the GameObject&#39;s lossy scale.
Definition: TSCollider.cs:109
Mesh Mesh
Mesh attached to the same game object.
override void DrawGizmos()
Draws the specific gizmos of concrete collider (for example "Gizmos.DrawWireCube" for a TSBoxCollider...
FP x
The X component of the vector.
Definition: TSVector.cs:37
List< TSVector > Vertices
A list of all mesh&#39;s vertices.
override Vector3 GetGizmosSize()
Returns the gizmos size.