Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unable to Get connectedAnchor to Connect in Correct Spot

Discussion in 'Scripting' started by Skyler_Hawkins, Jun 21, 2018.

  1. Skyler_Hawkins

    Skyler_Hawkins

    Joined:
    Aug 18, 2016
    Posts:
    32
    I've been unable to get my DistacneJoint2D 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 exact point of collision of the collider it hits with, and every one doesn't seem to work for me.

    I've tried changing my code around to use ContactPoints2D but when I do this it never actually changes the connectedAnchor and stays stuck at (0,0).


    Code (CSharp):
    1.  
    2. public DistanceJoint2D joint2D;
    3.  
    4. public void Awake()
    5.     {
    6.         joint2D = GameObject.FindGameObjectWithTag("Player").GetComponent<DistanceJoint2D>();
    7.         joint2D.enabled = false;
    8.         joint2D.GetComponent<DistanceJoint2D>().enableCollision = false;
    9.         }
    10. private void OnCollisionEnter2D(Collision2D collision)
    11.     {
    12.         joint2D.enabled = true;
    13.         joint2D.GetComponent<DistanceJoint2D>().enableCollision = true;
    14.         joint2D.connectedAnchor =collision.transform.position;
    15.         joint2D.distance = Vector2.Distance(joint2D.transform.position,collision.transform.position);
    16. }