- Home /
Rotating and balancing HingeJoint2D with mouse drag
I am trying to implement physics, similar to this game:
https://sites.google.com/site/newstudyhall/games/tilt-2
I have a “Hand” sprite, which is Kinematic and have a HingeJoint2D on it. Another sprite “Stick”, which is not Kinematic, is connected to hand through HingeJoint2D. I want to balance the Stick on hand by moving the hand.
I have attached following script with hand. I am moving the hand with mouse drag and applying force on stick in opposite direction of mouse movement. But it is not working as in above mentioned game.
Is there any component in Unity, which I can use to produce this result or how can I implement it? Any help is much appreciated. Thanks.
private Vector3 screenPoint;
private Vector3 offset;
void FixedUpdate()
{
//ON CLICK
if (Input.GetButtonDown("Fire1"))
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
}
//ON DRAG
if (Input.GetButton("Fire1"))
{
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
//HAND POSITION CHANGE WITH MOUSE DRAG
Vector2 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
//APPLY FORCE ON TRAY IN OPPOSITE DIRECTION OF MOUSE MOVEMENT
GameObject.Find("Stick").GetComponent<Rigidbody2D>().AddForce(((cursorPosition.normalized * 5)) * -1, ForceMode2D.Impulse);
}
}
Your answer
Follow this Question
Related Questions
Mouse rotation with limits: limit overrun protection works on positive overruns only? 0 Answers
Rotate 2d object on mouse drag relative to its position 1 Answer
Strange Problem with Torque-based Rotation 0 Answers
How will we give from a fixed point to rotate operation by using mouse? 1 Answer
Drag to rotate GameObject 4 Answers