I’ve not really given much though on this as it’s on the list of to-do’s, but I’ll post it here:
I have an object that needs to be inside a collision mesh before a visual process can be started.
The box is dragged inside this convex object (as pictured), and once inside it can be removed.
I’ve briefly tried with having four cubes on each corner and checking - if all four are in the collision mesh, then the next process should be true, but a single collision mesh on an object doesn’t work like that I have discovered and it’s going to take a bit more work.
I was thinking of just having four independent collision meshes instead of one, and once the cubes are aligned, that should do it, but are there more efficient ways of doing this? Maybe raycast to align with a point on the opposite surface? Help appreciated unity chumz.
If both objects in question are box-shaped it should be pretty straightforward.
Get the 8 corners of the dumpster and check if each of them are contained within the target. As long as the target object has a box collider you can just do call collider.bounds.Contains() for each point:
This will work best if the target box is axis-aligned, since collider bounds are Axis-Aligned bounding boxes.
You can get the 8 corners of your dumpster by attaching 8 empty GameObjects to the corners of it, or using a simple cube mesh scaled (without a renderer) on a child object of the dumpster and reading the vertex positions of that cube mesh in world space.
2 Likes
I never knew about bounds Contains() - thanks for that!
Actually the Raycast works pretty well here, with placement and alignment depending on the dimensions of the ‘layermask’ target- but I’ll come back to the bounds thing if this isn’t ideal. 
The object will just align with a pre set object once the conditions are matched.
If the thing self-aligns after you get close enough, I’ve totally done something similar!
1 Like
Was it just a simple translate you used there? I was just going to use a clunky reposition, I didn’t want to pushing anything in the vicinity round and causing physics problems.
It’s a simple position and rotation interpolation in a coroutine. Before I do it I also make the Rigidbody kinematic so there’s no physics based bumping/bouncing going on and I can then manipulate the transform directly. This code is on the “slot” which is the stationary object:
var currentPosition = insertMe.transform.position;
var currentRotation = insertMe.transform.rotation;
var targetPosition = transform.position;
var targetRotation = insertMe.ClosestValidOrientation(transform.rotation);
float time = 0;
while (time < LerpDurationOnAttach) {
time += Time.deltaTime;
var t = time / LerpDurationOnAttach;
insertMe.transform.position = Vector3.Lerp(currentPosition, targetPosition, t);
insertMe.transform.rotation = Quaternion.Lerp(currentRotation, targetRotation, t);
yield return null;
}