# How to move objects away from each other (not what you think)

I am making a game where I can drag objects around, but they can’t go far inside each other, so I made it so that the dragging function doesn’t work even if they are slightly inside. Then, in order for the drag function to work again, the objects need to move away from each other. This is where I have problems. The parts of the code I am talking about are in the onmousedrag method, so everything only works if the mouse is held down. This is why neither Vector2.movetowards nor transform.Translate work. The objects also can’t have rigidbodies so adding a force doesn’t work. I need help. The game is 2D.

`````` private void OnMouseDrag()
{
if (snapHall == null) return;
HallwayBehavior otherHall = snapHall.GetComponent<HallwayBehavior>();

Vector2 pos = transform.position;
Vector2 snapHallPos = snapHall.transform.position;

float xdiff = Mathf.Abs(pos.x - snapHallPos.x);
float ydiff = Mathf.Abs(pos.y - snapHallPos.y);

int z = Mathf.Abs(Mathf.RoundToInt(rot.z));
int otherZ = Mathf.Abs(Mathf.RoundToInt(otherHall.rot.z)); //the vector rot is basically the rotation of the gameobject

bool inside = false;

if(  (z == 180 || z == 0) && (otherZ == 180 || otherZ == 0)  )
{
if (xdiff < 6 && ydiff < 2.5f)
{
inside = true;
}
else inside = false;
}

if (!inside)
{
Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f);
transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset; //These two lines are for dragging
}
else
{
//this is when the object needs to move away
}
}
``````

Ok, I’m sorry, I don’t know what is what with those variable names.

You will need a couple of variables for this script:

``````Vector3 lastObjectPosition;
Collider2D lastObjectCollider;
GameObject currentObject;
``````

Then when you grab an object, you change the lastObjectPosition to something like this:

``````currentObject = WhateverObjectYouSelectedWithMouse
lastObjectCollider = currentObject.GetComponent<Collider2D>();
lastObjectPosition = new Vector 3 ((currentObject.transform.position.x - lastObjectCollider.size.x), currentObject.transform.position.y, currentObject.transform.position.z);
``````

then when collect a new object, you just run that code again.

this should snap the object directly behind the one that is in last.

Sorry if I didn’t explain it well or it doesn’t work like you need it to.