Math question: How to move/extrude a cube's face in Unity?

The short question is: What's the math to move the face of a cube? I.e. how to stretch (or shrink) a cube in the direction of one of its faces?

Here's a picture:

The camera shows a cube (left). When the user clicks and drags on one of the faces (yellow), the face (it's vertices) should follow the mouse and as a result expand (or shrink) the cube in the given direction (like the right cuboid in the picture above).

Please note that this should be done ingame, by moving the vertices, not by scaling the object.

Now, I already have the selected face and all the vertices of its four corners. Further, the distance how far it should be moved is also known. The question is, what needs to be done with the vertices to pull the face out (or push it in)? Whats the math?

Your help is very much welcome. Thank you.

• Do you want to enable the player to do that ingame or do you want to do that in the Unity editor? Commented Dec 14, 2020 at 16:56
• That should be ingame. I've updated the question. Commented Dec 14, 2020 at 17:05

You said you know the distance, then you just need to figure out the direction too. You simply move each of those vertexes that distance in that direction.

To move it “outwards” and “inwards”, what you’re talking about is moving it along the face’s normal vector.

Not sure if unity has any built in functions for this, but basically 3 of the vertices are enough to define a plane. You need the normal of this plane, convert it to a unit vector (magnitude 1) then you can multiply it by the distance, with negative numbers being inwards, and positive numbers outwards.

I suspect meshes in unity already have a normal vector saved that is associated with each face since these normals are required for materials and textures applied to meshes.

• Yes, the direction. That's it! How do you find it? Commented Dec 14, 2020 at 17:40
• Do you just want to extrude it outwards from the face? Commented Dec 14, 2020 at 17:41
• The face should move in both directions, outwards and back. Commented Dec 14, 2020 at 17:42
• Edited answer above Commented Dec 14, 2020 at 17:46