0
\$\begingroup\$

I want to create a trigger-collider between two boxes. When one of the boxes moves, the trigger is supposed to change its size and shape so that its left and right edge stay attached to the two boxes.

How can I implement this in C# or JavaScript?

enter image description hereenter image description here

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Get the two points on the side of the boxes

// Assuming that `box1` and `box2` are meshes
// Find the right side of box1 and left side of box 2

// `bounds` is the bounds of the mesh, so (max, center, center) 
// is in the middle of the right face of the box
Vector3 box1r =  new Vector3(box1.bounds.max.x, 
        box1.bounds.centre.y,
        box1.bounds.center.z);

// in a similar way, (min, center, center) is the left side of the box
Vector3 box2l = new Vector3(box2.bounds.min.x,
        box2.bounds.center.y,
        box2.bounds.center.z),

The location of the trigger should always be in the centre of the two boxes:

trigger.position = Vector3.Lerp( // `Lerp` returns a point between two other points
    box1r, box2l, // Take a point between the boxes
    0.5f); // 0.5 means take the center of those two points

Wether to change the trigger's Center position or the position of its Transform is up to you, this is pseudocode-like.

Then you need to resize the trigger, equal to the distance of the boxes:

trigger.scale = new Vector3(
    Vector3.Distance(box1r, box2l), // Its scale on X axis is exactly the distance of the boxes
    // This makes its scale on Y and Z axis the same as box1's size on that axis
    // This depends on your situation, are the two boxes the same size?
    // Can they change size?
    box1.bounds.extends.y, 
    box1.bounds.extends.z,

The last part is to rotate the trigger in such a way that it connects the two boxes, I'm not very good with rotations, so I have this lazy way:

// Makes the trigger's front axis to look towards the right box
trigger.LookAt(box1r);

// Rotates the trigger 90 degrees on the Y axis, to make it's side point to the box's side (this might be -90 instead, depending on your objects)
trigger.Rotate(Vector3.up *90f);

Depending how your objects are placed in your project, you might need to do some adjustments on some numbers. Also the trigger, will not align perfectly. As far as I know, it's impossible to change the shape of the trigger outside of primitive shapes or fixed meshes, so this method assumes the trigger will always remain a cube:

enter image description here

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .