- Home /
Rotating an object in relation to its endpoints
Hey,
In the app I am making the user places objects on the ground and a line is supposed to appear between them, so that they are connected. I managed to instantiate and scale it correctly but when it comes to rotation... after a few hours I still cannot figure out how it should be. The endpoints' coordinates can be different in all axes - they are not in the same plane. Here's my funtion:
void PlaceLine(Vector3 startPos, Vector3 endPos)
{
// calculating the center point between two endpoints
Vector3 centerPos = new Vector3(startPos.x + endPos.x, startPos.y + endPos.y, startPos.z + endPos.z) / 2f;
// instantiating the line in the center point with an appropriate rotation
GameObject line = Instantiate(linePrefab, centerPos, Quaternion.FromToRotation(endPos, startPos));
// calculating the scale of the line
float scaleX = Mathf.Abs(startPos.x - endPos.x);
// setting the line's length
line.transform.GetChild(0).localScale = new Vector3(scaleX, 0.001f, 0.03f);
}
I've also tried using Quaternion.LookRotation and some other ways but none of them worked for me either. I don't like quaternions and they don't like me, I guess...
Answer by Bunny83 · Apr 09, 2020 at 11:54 AM
if you use a Quad or cube as a line there's a really simple trick. First of all parent your unit quad / cube to an empty gameobject and offset the child by half its size along the z axis so that the origin of the parent sits right at the end of the quad / cube and the object extends along the positive z axis. Make this construct a prefab.
To align such a prefab between two points all you have to do is this:
public Transform linePrefab;
Transform PlaceLine(Vector3 startPos, Vector3 endPos)
{
Transform line = Instantiate(linePrefab);
line position = startPos;
line.LookAt(endPos);
line.localScale = Vector3.forward * Vector3.Distance(startPos, endPos);
return line;
}
Note that you can adjust the child objects local scale for x and y to adjust the thickness. However the length in z should stay at 1 since the parent scale will directly determine the length of the line. Also note that the LookAt method has an optional up vector as second parameter. It can be used to control the rotation around your line in 3d space. If you use this for 2d you probably want pass -Vector3.forward
as up vector so the top side of your object will face the camera.
$$anonymous$$aybe Transform.RotateAround ? Transform.RotateAround(startPoint, cross(start, end), vector.angle(start, end)) ?