# Rotating cube based on four vector3s

I’m trying to approximate the size and rotation of a single box collider(cube) based on a dynamic mesh in 3D space. This dynamic mesh(quad) is drawn from four vector3s.

It doesn’t need to be exact, but I’m having issues creating a rotation for the box collider. Here’s a gif showing the issue using spheres for the four positions and a center cube to visualize the box collider

This was an attempt to use Quaternion.FromToRotation, and then get the Euler angle for the X rotation. As you can see it has an issue going above 90° or below -90°.

I got it working on two axis’ when I used transform.LookAt, but I need it to work on all 3 axis’.

Is this possible? Any ideas on what else I could try? Thank you!

Here’s the code I’m working with if you want to mess with it:

``````    [SerializeField] Transform[] fourCorners;
[SerializeField] GameObject centerCube;
Vector3 centerPosition;

private void Update(){
//position and scaling
centerPosition = Vector3.zero;
foreach (Transform trans in fourCorners){
centerPosition += trans.position;
}
centerPosition = centerPosition / 4;
centerCube.transform.position = centerPosition;
var zMagnitude = (fourCorners[0].position - fourCorners[1].position).magnitude;
var xMagnitude = (fourCorners[1].position - fourCorners[2].position).magnitude;
var localScale = centerCube.transform.localScale;
localScale.z = zMagnitude;
localScale.x = xMagnitude;
centerCube.transform.localScale = localScale;

//Rotation attempts
var rightCenter = (fourCorners[0].position + fourCorners[1].position) / 2;
//centerCube.transform.LookAt(rightCenter);
var frontCenter = (fourCorners[1].position + fourCorners[2].position) / 2;
var backCenter = (fourCorners[0].position + fourCorners[3].position) / 2;
var xAngle = Quaternion.FromToRotation(Vector3.forward, (frontCenter-backCenter));
var localEuler = centerCube.transform.localEulerAngles;
var quatToEul = xAngle.eulerAngles.x;
localEuler.x = quatToEul;
centerCube.transform.localEulerAngles = localEuler;
//centerCube.transform.rotation = xAngle;
}
``````

Seems I fell victim to the age-old “trying to input quaternions manually”

multiplying the calculated quaternions by the current rotation did the trick:

``````        centerCube.transform.rotation = Quaternion.FromToRotation(centerCube.transform.right, (frontCenter - backCenter)) * centerCube.transform.rotation;
centerCube.transform.rotation = Quaternion.FromToRotation(centerCube.transform.forward, (lefCenter - rightCenter)) * centerCube.transform.rotation;
``````