Question by
unity_865E76FCAAEEDB577C33 · Jun 01 at 04:02 AM ·
collision2drecttransformrect
Convert two contact points in world space to size width in rect
I have two contacts points inside a collision, and I have tried to transform these contacts in width of a new rect, for fake cut sprite purpose, I read all documentations about Rect, and Collision, and nothing helped me, can anyone give me a fresh breeze about that. this is the code:
void OnCollisionEnter2D(Collision2D target)
{
// Make an empty list to hold contact points
ContactPoint2D[] contacts = new ContactPoint2D[target.contactCount];
// Get the contact points for this collision
int numContacts = target.GetContacts(contacts);
var sprite = GetComponent<SpriteRenderer>().sprite;
var a = contacts[0].point;
var b = contacts[contacts.Length - 1].point;
Cut(a, b);
}
void Cut(Vector2 cutPositionA, Vector2 cutPositionB)
{
var sprite = GetComponent<SpriteRenderer>();
Texture2D _texture = sprite.sprite.texture;
Sprite newSprite = Sprite.Create(_texture, new Rect(cutPositionA.x, 0f, cutPositionB.x, 512f), new Vector2(0.5f, 0.5f), 512f);
GameObject sprGameObj = new GameObject();
sprGameObj.transform.localScale = sprGameObj.transform.localScale + new Vector3(1f, 1f, 0f);
sprGameObj.AddComponent<SpriteRenderer>();
SpriteRenderer sprRenderer = sprGameObj.GetComponent<SpriteRenderer>();
sprRenderer.sprite = newSprite;
sprGameObj.transform.position = new Vector3(cutPositionA.x, cutPositionA.y);
sprRenderer.sortingOrder = 1;
sprGameObj.AddComponent<BoxCollider2D>();
var bc = sprGameObj.GetComponent<BoxCollider2D>();
bc.offset = new Vector2(0f, 0.06f);
bc.size = new Vector2(1f, 0.7f);
var rb = sprGameObj.AddComponent<Rigidbody2D>();
rb.drag = 2f;
rb.angularDrag = 3f;
rb.mass = 1f;
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613061229im_/https://answers.unity.com/themes/thub/images/avi.jpg)