- Home /
Move spheres to form triangle
Hello,
I need to set the position of 3 spheres in order to look like the 3 points of a triangle.
I want to set the distance between the points and move the spheres to the correct position.
For example if I say I want A to have distance of 3 with B, B have distance of 4 with C and C have Distance of 5 with A, it will make a triangle 3,4,5
How Can I do this? Do I need to use Mathf.Distance?
Answer by Bunny83 · Aug 24, 2013 at 01:20 PM
This is way too unspecific. A triangle is a 2 dimensional object. If you place it in a 3d world there are unlimited ways how this triangle is positioned in space.
Next thing is if you don't have any reference, how and where should it positioned?
Lets start with some assumptions:
Let A always be at 0,0,0
We construct the triangle in the x-y plane, so all points have a z value of 0
We position B always on the y axis
With that additional information you can calculate the position of C
// C#
var a = 3.0f;
var b = 4.0f;
var c = 5.0f;
var A = new Vector3(0, 0, 0);
var B = new Vector3(0, c, 0);
var cos = (b*b + c*c - a*a) / (2*b*c);
var alpha = Mathf.Acos(cos);
var sin = Mathf.Sin(alpha);
var C = new Vector3(sin*b, cos*b, 0);
Note: this works perfectly, but only with valid values for a, b and c. For example a+b can't be larger than c. in such a case the calculation would fail and produce NaNs ...