Click and drag an object together with a separate object
Hey,
I want to move an object around in my 2D project using my mouse input, which works fine so far, but at the same time a different object should move as well. It should work as if the second object was a child of the first one, so that is moved in the same way, but not right below the mouse. While this is easily done when they are parent and child, my objects are not.
From the object I am dragging, I do have a reference to the second object, but how do I move it along? The only method I could think of right now would be some arithmetic on transform.position with explicit numbers but I cannot imagine there is no other way than that.
I don't know if this is relevant but here is my code for moving so far:
void OnMouseDown() {
pressed = true;
if (!isClone) {
if (transform.parent.name.Contains("AND")) {
clone = Instantiate(Resources.Load("FB/FunctionBlock_AND")) as GameObject;
...
}
}
screenPoint = Camera.main.WorldToScreenPoint (gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
and
void OnMouseDrag() {
Vector3 curScreenPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z); // Current touch point
Vector3 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint) + offset; // Current touch point converted to point in scene
if (!isClone) {
clone.transform.position = curPosition; // Move clone to this position
} else {
// transform.position = curPosition; // non clamped version
// Mathf.Clamp() restricts the movement of the dragged FB to the working area
transform.parent.position = new Vector3 (
Mathf.Clamp (curPosition.x,
(breadboardLeft.position.x+breadboardLeft.GetComponent<BoxCollider2D>().bounds.size.x)+0.4f,
breadboardRight.position.x-breadboardRight.GetComponent<BoxCollider2D>().bounds.size.x),
curPosition.y,
curPosition.z);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612164054im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Game object position is stuck when using mathf.sin,Object's position stuck when using Math.sin 0 Answers
Creating a train system with little to no code knowledge 0 Answers
How to move a ball to left and when it hits the wall should go towards right and thus continues? 0 Answers
I need help with my flying script 0 Answers
moving object dissapears when it reaches it's destination 0 Answers