- Home /
How to get a Distance Joint 2D to connect to my player GameObject?
I have my player fire a projectile, and where it hits terrain it creates my gameObject HookPoint. How do I get my HookPoint to have its Distance Joint 2D to be Connected to the player, which is already in the scene?
Answer by AaronBacon · Aug 22, 2021 at 12:10 PM
What you'd want to do is change "̶a̶t̶t̶a̶c̶h̶e̶d̶R̶i̶g̶i̶d̶b̶o̶d̶y̶"̶ "connectedBody" on the Joint2D component to your players rigidBody2D component. How you do that will depend on how your scene Is set up, but a script like this on the HookPoint Object might work:
⠀
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HookPoint: MonoBehaviour
{
// Awake will be called when the object is instantiated
public void Awake()
{
Joint2D joint = GetComponent<Joint2D>();
GameObject player = GameObject.FindGameObjectWithTag("Player");
joint.connectedBody = player.GetComponent<Rigidbody2D>();
}
}
⠀
Worth noting this method requires the player to be tagged as "Player" in the inspector:
⠀
I tried this and it all makes sense to me, but it won't let me set the attached rigidbody, clai$$anonymous$$g that is read only. The actual error I get is: Property or indexer 'Joint2D.attachedRigidbody' cannot be assigned to -- it is read only
I'm assu$$anonymous$$g that that just means I cannot change what my attached rigidbody is through script. Is there anything I can do about that?
Sorry, that's my mistake, the variable you want to edit is connectedBody, not attachedRigidbody: https://docs.unity3d.com/ScriptReference/Joint2D-connectedBody.html
I tested in Unity and as long as the component is set up correctly, it snaps onto the player automatically
Your answer
Follow this Question
Related Questions
Wheel Friction Curve in 2d 0 Answers
2D Physics: How to have a character "grab" onto wall with hand 0 Answers
Creating a movement script to move up and down a chain (or rope) in a 2D game 1 Answer
Unexpected behaviour with Fixed Joint 2D 0 Answers
is there a 2d joint that does not affect the rotation of the connected rigidbody2d? 0 Answers