///<summary>Breaks the object across a line and flings its pieces away from the center at the given force. Set spawn to false to prevent the pieces from spawning</summary> private object[] Break(Mesh mesh, float force, Vector2 from, Vector2 to, bool spawn = true) { from = RelativePoint(from); to = RelativePoint(to); Vector3[] breakPoints = GetBreakPoints(mesh, from, to), weakSide, strongSide; GetSides(mesh, from, to, out weakSide, out strongSide); MeshAt weakFracture = CreateFractureMesh(weakSide, breakPoints); MeshAt strongFracture = CreateFractureMesh(strongSide, breakPoints); List <object> fractures = new List <object>(); if (spawn) { fractures.Add(CreateFractureObject(weakFracture, gameObject)); fractures.Add(CreateFractureObject(strongFracture, gameObject)); } else { fractures.Add(weakFracture); fractures.Add(strongFracture); } fractures.RemoveAll(obj => obj == null); if (spawn) { BlastApart(fractures.ConvertAll(f => (GameObject)f).ToArray(), force); } return(fractures.ToArray()); }
///<summary> ///Creates a new fracture from the mesh and it's center based on this object, then returns it. ///Returns null if the mesh is null or if the area is too small ///Additionally corrects mass relative to area based on the original if provided ///</summary> GameObject CreateFractureObject(MeshAt meshAt, GameObject original = null) { if (meshAt != null) { float area = GetArea(meshAt.mesh); if (area < minFractureArea) { return(null); } GameObject fractureObject = Instantiate(gameObject, transform.position + meshAt.center, original == null ? transform.rotation : Quaternion.identity); fractureObject.GetComponent <MeshFilter>().mesh = meshAt.mesh; fractureObject.name = gameObject.name; fractureObject.GetComponent <BreakableObject>().FormatBreakable(); if (original != null) { float originalMass = original.GetComponent <Rigidbody2D>().mass; float originalArea = GetArea(original.GetComponent <MeshFilter>().mesh); fractureObject.GetComponent <Rigidbody2D>().mass = area / originalArea * originalMass; fractureObject.GetComponent <Rigidbody2D>().velocity = original.GetComponent <Rigidbody2D>().velocity; fractureObject.GetComponent <Rigidbody2D>().angularVelocity = original.GetComponent <Rigidbody2D>().angularVelocity; fractureObject.GetComponent <BreakableObject>().maxHealth = fractureObject.GetComponent <BreakableObject>().health = area / originalArea * maxHealth; fractureObject.transform.parent = original.transform.parent; fractureObject.transform.RotateAround(original.transform.localPosition, Vector3.forward, original.transform.eulerAngles.z); } return(fractureObject); } return(null); }