Hello, so i do not know how to make it because i am a beginner.
A script for 2D Squares to snap together when they touch.
The game you try to make is a stacker like game (its just a mini project).
I would like to make it so when the block hits the ground/another block it snaps to it. Not like exactly one on another but how every it falls. But if the blocks is too much on the edge it shouldn’t snap to it but just fall.
I hope i was clear, if not i can try to explain(English isn’t my first language, sorry)
I think I understand what it is that you are asking for, though I could be wrong.
You’ll need a snap range
private float _snapRange = 0.05f;
You’ll then need to know the size of both objects.
float ObjectASize = 10f;
float ObjectBSize = 10f;
Then you’ll need to get the distance from ObjectA and ObjectB
float distance = Vector3.Distance(ObjectA, ObjectB);
Now subtract have the size of each object from the distance
float netDistance = distance - ((ObjectASize / 2) + (ObjectBSize / 2));
Now, check if netDistance is within your snap range and if so, snap it
if(Mathf.Abs(netDistance) < _snapRange)
{
// Perform your snap here
}
As far as performing the snap, let’s assume that ObjectA is over ObjectB and that when it snaps it should end up with the same X and Z values
Vector3 targetPos = ObectB.transform.position;
targetPos.Y = ObjectB.transform.position + (ObjectASize / 2) + (ObjectBSize / 2);
ObjectA.transform.position = targetPos;