get two rigid body cubes to line up side by side

I have some rigid body cubes that when they collide, I set the orientation so they are facing the same way and I joint them together, but i cant seem to figure out how to get them positioned so they are lined up perfectly side by side. I am currently using the point of collision so one is usually a little more forward or up

My initial thoughts were to take the center point of whichever rigid body i deem the ‘parent’ and subtract half of the width, but I cant tell which axis to add or subtract the half-width from as they both rotate on their own. I’m guessing I need to take the forward direction of the parent cube into account but not sure what else I need to do.

I tried searching this but the search seemed to be not working =-(

How are you joining them? Parent child? Combining meshes? How do you decide which is the parent?

Sorry, was out the rest of the day. I am determining parent based on which cube was created first. So if i toss one rigid body in the scene and then another one, the first rb would be considered the parent if they come in contact.

1 Answer

1

I was hoping for an answer with respect to how you are joining so I could provide a full example. But here is the core of what I might do:

function ClosestAxis(v3 : Vector3, trans2 : Transform) : Vector3 {
	var v3Ret : Vector3 = Vector3.zero;
	var fAngle = Mathf.Infinity;
	var fT : float;
	
	fT = Vector3.Angle(v3, trans2.forward);
	if (fT <= fAngle) { fAngle = fT; v3Ret = trans2.forward; }
	fT = Vector3.Angle(v3, trans2.up);
	if (fT <= fAngle) { fAngle = fT; v3Ret = trans2.up; }
	fT = Vector3.Angle(v3, trans2.right);
	if (fT <= fAngle) { fAngle = fT; v3Ret = trans2.right; }	
	fT = Vector3.Angle(v3, -trans2.forward);
	if (fT <= fAngle) { fAngle = fT; v3Ret = -trans2.forward; }
	fT = Vector3.Angle(v3, -trans2.up);
	if (fT <= fAngle) { fAngle = fT; v3Ret = -trans2.up; }
	fT = Vector3.Angle(v3, -trans2.right);
	if (fT <= fAngle) { fAngle = fT; v3Ret = -trans2.right; }	
	
	return v3Ret;
	}

The initial v3 can either be one of the contact points, or it can be the position of the other cube. It needs to be a relative position, so it might be used:

var v3Axis = ClosestAxis(transform.position - collision.collider.transform.position, collision.collider.transform); 

Once you have the axis, you can move the block to a position on this axis:

transform.position = transform.position = collision.transform.position + v3Axis * blockWidth;

Thanks for this, I'll check it out when i have a chance and let ya know =-)