- Home /
Swapping 2 objects positions when one is dragged into the other
I have 2 cubes lined up side by side that I would like to have swap positions/location when dragged against each other. So if Cube1 is dragged into Cube2 they would swap positions.
I attempted using the below code that was posted on the Unity forums but have not received good results. It initially swaps fine on the first drag/collision and both objects swap positions, but when dragging them together again for the second collision the objects do not go to the correct positions. The code/script is on both cubes:
private var thisTransform : Transform; var startPosition : Vector3; private var script : objectSwitch;
function Start() { thisTransform = GetComponent(Transform); startPosition = thisTransform.position; }
function OnCollisionEnter ( other : Collision) { var tempPosition = other.transform.position;
other.transform.position = startPosition; startPosition = tempPosition;
}
function resetPosition() { thisTransform.position = startPosition; }
Answer by Fuller · May 30, 2010 at 01:00 AM
Try swapping the position of only the local object. e.g:
function OnCollisionEnter ( other : Collision) { var tempPosition = other.transform.position;
startPosition = tempPosition;
}
Dunno if that'll work. Just a quick thought.