- Home /
Hinge joints disconnect when pulled too far.
I have this chain that consists of a bunch of hingejoints connected together. I want to control this chain with the mouse but when the mouse gets too far away the chain starts to disconnect and act weird. I want the chain to stop extending when its been pulled to its max length but still follow the mouse.
Heres some code:
mouseX = Input.mousePosition.x;
mouseY = Input.mousePosition.y;
Vector2 mousePos = cam.GetComponent<Camera>().ScreenToWorldPoint(new Vector2(mouseX, mouseY));
rb.MovePosition(mousePos);
Sorry for bad explanation.
From the length of the segments and their distances you should be able to calculate the maximum length of the chain. I assume it's connected on one end and you're moving the other end. What you could do is restrict the mouse position to the maximum length of the chain from it's anchor.
If distance > maxLength, calculate direction Vector from anchor to mouse, clamp it's magnitude and add it to the anchor position. That's your new mouse position
Okay I came up with some restriction but now the cahin seems to be... sagging? if i hold the mouse still the last link will start falling. Anyway to avoid this?
The wheight of the chain probably makes it stretch and become a bit longer than its calculated length. You might just have to add a few percent to the length of the calculated clamped mousePosition
Okay I didnt actually use the clamp thing but I put the gravity scale to 0 on the object and increased the mass. Im gonna put my script here if anyone needs it.
GameObject cam;
public Transform center;
public float radius;
float dist;
Vector2 mousePos;
Vector2 screen$$anonymous$$ouse;
Vector2 mouseOffset;
void Start()
{
cam = GameObject.FindGameObjectWithTag("$$anonymous$$ainCamera");
}
void Update()
{
mousePos = Input.mousePosition;
screen$$anonymous$$ouse = cam.GetComponent<Camera>().ScreenToWorldPoint(new Vector2(mousePos.x, mousePos.y));
mouseOffset = new Vector2(screen$$anonymous$$ouse.x - center.position.x, screen$$anonymous$$ouse.y - center.position.y);
transform.position = new Vector2(screen$$anonymous$$ouse.x, screen$$anonymous$$ouse.y);
dist = Vector2.Distance(new Vector2(transform.position.x, transform.position.y), new Vector2(center.position.x, center.position.y));
if(dist > radius){
Vector2 norm = mouseOffset.normalized;
transform.position = new Vector2(norm.x * radius + center.position.x,
norm.y * radius + center.position.y);
}
}
This is still test code btww so I know theres some stuff I could probably do differently
Thanks for the help.