Question by
Skyler_Hawkins · Jun 22, 2018 at 05:18 PM ·
collisionjointsanchor
How to get ConnectedAnchor to the Point of Collision?
I've been unable to get my DistanceJoint2D to connect at the contact point of the Collider. I have this script attached to a prefab that I fire out and when it hits an object it gets the position of the gameObject for the connectedAnchor, however it's the center of the gameObject and not the point of contact of the gameObject how I would like it too. I've been try several different way to get it to connect at the exact point of collision of the collider it hits with, and none of them seem to work for me.
public DistanceJoint2D joint2D;
public void Awake()
{
joint2D = GameObject.FindGameObjectWithTag("Player").GetComponent<DistanceJoint2D>();
joint2D.enabled = false;
joint2D.GetComponent<DistanceJoint2D>().enableCollision = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
joint2D.enabled = true;
joint2D.GetComponent<DistanceJoint2D>().enableCollision = true;
joint2D.connectedAnchor =collision.transform.position;
joint2D.distance = Vector2.Distance(joint2D.transform.position,collision.transform.position);
}
Comment
Best Answer
Answer by Skyler_Hawkins · Jun 22, 2018 at 05:58 PM
Well, it's always funny how you end up fixing something right after you ask a question.
public DistanceJoint2D joint2D;
public void Awake()
{
joint2D = GameObject.FindGameObjectWithTag("Player").GetComponent<DistanceJoint2D>();
joint2D.enabled = false;
joint2D.GetComponent<DistanceJoint2D>().enableCollision = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
ContactPoint2D onContactPoint = collision.contacts[0];
joint2D.enabled = true;
joint2D.GetComponent<DistanceJoint2D>().enableCollision = true;
joint2D.connectedAnchor = onContactPoint.point;
joint2D.distance = Vector2.Distance(joint2D.transform.position,onContactPoint.point);
}