Hinge Joint 2d not working properly in my Unity script

Issue

This Content is from Stack Overflow. Question asked by VG- VovaGatova

I decided to move objects with the mouse. Everything worked out, but I decided to make everything more realistic and added Hingle Joint 2d
And it doesn’t work at all. If you disable ConnectedBody in the code, then the object will attach with its Achor in the wrong direction at all

Ps: I tried to change the value of Mouse to MouseTransofrm

CODE :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragItems : MonoBehavior
{
public Rigidbody2D selectedObject;
public HingeJoint2D StopCenter = null;
public Rigidbody2D obj;

public Vector2 Mouse;
public Transform Mousetransform;
vector3 offset;
Vector3 mousePosition;
public float maxSpeed=10;
Vector2mouseForce;
Vector3 lastPosition;
void Update()
{
Mouse = Mousetransform.transform.position;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (selectedObject)
{
mouseForce = (mousePosition - lastPosition) / Time.deltaTime;
mouseForce = Vector2.ClampMagnitude(mouseForce, maxSpeed);
lastPosition = mousePosition;
}
if (Input.GetMouseButtonDown(0))
{
Collider2D targetObject = Physics2D.OverlapPoint(mousePosition);
if (targetObject)
{
selectedObject = targetObject.transform.gameObject.GetComponent();
offset = selectedObject.transform.position - mousePosition;
}
}
if (Input.GetMouseButtonUp(0) && selectedObject)
{
selectedObject.velocity = Vector2.zero;
selectedObject.AddForce(mouseForce, ForceMode2D.Impulse);
selectedObject = null;
}
}
void FixedUpdate()
{
if (selectedObject)
{
selectedObject.MovePosition(mousePosition + offset);
StopCenter = selectedObject.GetComponent();
StopCenter.enabled = true;
StopCenter.connectedBody = obj;
StopCenter anchor = Mouse;
}

}
}



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?