unity-game-engine2dcoordinatesspritescaling

Shrink a rotating object up to point


I have an object (orange) that is tied to a hinge joint (black) and can rotate around it. At some point when I detect collision with other object I have to cut it there (red). In order to do that I want to shrink the object between those points (black and red), but I need it to remain tied to the hinge joint and to keep its width. enter image description here

void OnCollisionEnter2D(Collision2D collision)
{
    GameObject obj = collision.gameObject;
    Vector3 endPos =collision.contacts[0].point;
    float scaleX = Vector3.Distance(new Vector3(startPos.x, 0, 0), new Vector3(endPos.x, 0, 0));
    float scaleY = Vector3.Distance(new Vector3(0, startPos.y, 0), new Vector3(0, endPos.y, 0));
    Vector3 newScale = new Vector3(scaleX,scaleY, 1);
    obj.transform.parent.transform.localScale = obj.transform.TransformPoint(newScale);
}

And the start position is initialized by the position of the hinge joint:

startPos = GameObject.Find("hair").GetComponent<HingeJoint2D>().transform.position;

I wrapped the object in parent and scaled it, because I read somewhere that then it would remain in place:

enter image description here

I tried many things, but I can’t get it to stay in place and be in right size. How can I implement it right?


Solution

  • If you move the pivot (position) of the parent transform to the hinge, then you apply the localScale to the parent object you will achieve the desired result.

    enter image description here

    Example:

    private float scale = 3;
    

    And then:

    transform.parent.transform.localScale = new Vector3(transform.parent.transform.localScale.x, transform.parent.transform.localScale.y, scale);