- Home /
The question is answered, right answer was accepted
Set targetjoint2d anchor position at mouse position in 2d
Hello everyone,
I am currently working on a physics puzzle game. I have a gameobject with a rigidbody2d, with a hingejoint2d component holding it in place. This causes the object to only rotate around the center on impact.
To rotate the object manually I am using a targetjoint2d, together with my mouse. The target of the targetjoint2d is set at my mouse position. To rotate the object, I want to set the anchor of the target joint at the position of the mouse, when the onmousedown function is called. The problem I have is that the anchor is currently being set in world space, while the anchor position of the target joint is calculated from the distance of the gameobject center.
How do I set the anchor at the position of my mouse when I click?
Below is the code for the object to be rotated:
public class Drag : MonoBehaviour
{
public TargetJoint2D tarJoint;
public bool moveAnchor = false;
bool canDrag = false;
private void FixedUpdate()
{
if (!canDrag)
return;
if (Input.GetMouseButton(0) == false) // when the mouse button is no longer pressed...
{
canDrag = false;
tarJoint.enabled = false;
return;
}
tarJoint.target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
void OnMouseDown()
{
tarJoint.enabled = true;
if (moveAnchor) // if true, the anchor is not set at the center of the object
{
tarJoint.anchor = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
canDrag = true;
}
}
This image shows the settings of the joints on my gameobject. It also has a rigidbody2d set to dynamic and a boxcollider 2d.
Follow this Question
Related Questions
Creating a movement script to move up and down a chain (or rope) in a 2D game 1 Answer
What is happening in HingeJoint2D motors? 1 Answer
Physics 2D and joints 0 Answers
2D Ground, really long, how? 1 Answer
Wheel Friction Curve in 2d 0 Answers