Well I am making a jigsaw like game (2d) I’ve run over many like question that suggested to parent objects together, well that will make one object follow the other but not vice versa I want to drag either of the two objects and the other move along.
Any help ?
I don’t know how you are approaching your drag and drop and your combining of pieces. Here is a bit of code as an example of how it may be done. This may not be the best approach for your specific mechanics, but it show a proof of concept. To make the code simple, each visible piece has an empty game object as a parent. If pieces are combined, one of the two parents is abandoned. As mentioned in my comments above, the drag and drop moves the empty parent game object, not the child piece.
#pragma strict
import System.Collections.Generic;
private var offset : Vector3;
function OnMouseDown () {
var v3 = Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.parent.position.z - Camera.main.transform.position.z);
v3 = Camera.main.ScreenToWorldPoint(v3);
offset = transform.parent.position - v3;
}
function OnMouseDrag() {
var v3 = Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.parent.position.z - Camera.main.transform.position.z);
v3 = Camera.main.ScreenToWorldPoint(v3);
transform.parent.position = v3 + offset;
}
function Combine(piece : GameObject) {
var transforms : List.<Transform> = new List.<Transform>();
var parent = piece.transform.parent;
var trans = transform.parent;
for (var child : Transform in transform.parent) {
transforms.Add(child);
}
for (var child : Transform in transforms) {
child.parent = parent;
}
}
Note that the combine code transfers all siblings to the new parent. This will allow two collections of more than one piece to be combined.