# Calculate distance from the centre to the edge of a cube in OpenGL

I'm trying to calculate the distance between a central point on a cube and anywhere on the surface of the cube, depending on the location of a second 3D point.

I have two vertices in 3D; Q and P. Q is the centre of the cube, P is a random point outside of the cube. I also have a known size of the cube, where distance across is d.

If I have the normalised vector of u, which is Q->P, how do I calculate the distance from the centre to where it hits the surface of the cube? I could not find the answer to this anywhere,on the Stack Exchange.

• It might be useful to know what your trying to do. Especially given that, as it currently stands, this question does not provide any context that is specific to game developing. In fact, this looks very much like a homework exercise. – Gnemlock Nov 26 '16 at 21:59
• I am trying to get a mesh to follow the shape of a cube in opengl. I've provided it with cube, it's got the dimensions, it knows the central point, and it has to manipulate the vertices of the mesh based on how close they are to the cube. It's not a homework exercise, but I can't think of any other way to phrase the question. – Jonathan Cain Nov 26 '16 at 22:12

Because your ray starts at the centre of the cube, you can easily tell which face of the cube it hits. Simply find the component of u that has the largest magnitude - it's one of the faces with normals pointing along that axis. The sign of that component will tell you which of those two faces it intersects.
For example, if u is (3, -5, 4) then it hits the face of the cube with its normal pointing in the (0, -1, 0) direction (probably the bottom one, but it depends on your coordinate system).
However, you can simplify that process. In our example, we know that the point of intersection on the y axis is -d/2. So you can just scale u by d/(2*5) to make the y component end up where we want it. That gives us (3d/10, -d/2, 4d/10). If I haven't made any silly mistakes that will be your intersection point on the cube.