public GameObject CreateObject(CutVictim original) { var obj = new GameObject("cut obj", typeof(CutVictim), typeof(Rigidbody2D)); var mesh = new Mesh { vertices = Positions.ToArray(), triangles = Triangles.ToArray() }; mesh.RecalculateNormals(); obj.GetComponent <MeshFilter>().mesh = mesh; obj.GetComponent <MeshRenderer>().material = original.Material; var collider = obj.GetComponent <PolygonCollider2D>(); collider.points = original.Collider.points; var rigidBody = obj.GetComponent <Rigidbody2D>(); var force = new Vector2(Random.Range(-5, 5), Random.Range(-5, 5)); rigidBody.AddForce(force, ForceMode2D.Impulse); return(obj); }
private Vector3 pos2; // planeとmeshの交点その2 public void Cut(Plane plane, CutVictim victim) { var group1 = new CutGroup(); var group2 = new CutGroup(); for (var i = 0; i < victim.Triangles.Length; i += 3) { var positions1 = new List <Vector3>(); var positions2 = new List <Vector3>(); var idx0 = victim.Triangles[i]; var idx1 = victim.Triangles[i + 1]; var idx2 = victim.Triangles[i + 2]; var vertices = new List <Vector3>(); var v1 = Vector3.Scale(victim.Vertices[idx0], victim.Scale) + victim.Position; vertices.Add(v1); var v2 = Vector3.Scale(victim.Vertices[idx1], victim.Scale) + victim.Position; vertices.Add(v2); var v3 = Vector3.Scale(victim.Vertices[idx2], victim.Scale) + victim.Position; vertices.Add(v3); // そのポリゴンの法線を計算しておく var normal = Vector3.Cross(victim.Vertices[idx2] - victim.Vertices[idx0], victim.Vertices[idx1] - victim.Vertices[idx0]); AllocateVertices(plane, vertices, positions1, positions2); // 1.グループ分け // どちらにもカウントがあるということはplateと交差しているポリゴンということ if (positions1.Count > 0 && positions2.Count > 0) { CalcCrossPoint(plane, positions1, positions2); // 2.planeとの交点を求める // 3.両方のグループともに交点を入れる positions1.Add(pos1); positions1.Add(pos2); group1.CapPositions.Add(pos1); group1.CapPositions.Add(pos2); positions2.Add(pos1); positions2.Add(pos2); group2.CapPositions.Add(pos1); group2.CapPositions.Add(pos2); } if (positions1.Count > 0) { var triangles = CreateTriangles(positions1, normal); var count = group1.Positions.Count; group1.Positions.AddRange(positions1); // 二つめ以降ならidxがずれることに注意 foreach (var idx in triangles) { group1.Triangles.Add(idx + count); } } if (positions2.Count > 0) { var triangles = CreateTriangles(positions2, normal); var count = group2.Positions.Count; group2.Positions.AddRange(positions2); // 二つめ以降ならidxがずれることに注意 foreach (var idx in triangles) { group2.Triangles.Add(idx + count); } } } // 蓋を作る group1.Capping(plane, true); group2.Capping(plane, true); // 4.2つのグループに分けたオブジェクトを作成する group1.CreateObject(victim); group2.CreateObject(victim); // 5.元オブジェクトを消去する Object.Destroy(victim.gameObject); }