- Home /
Connecting two spheres with a cylinder
I have a pair (or more) of spheres in my scene and I'm connecting them using a (C#) script that instantiates a cylinder prefab, then scales and rotate it. I'm using the following code (taken from this answer):
// Position it
transform.position = (v3End-v3Start)/2.0f + v3Start;
var v3T = transform.localScale; // Scale it
v3T.y = (v3End-v3Start).magnitude;
transform.localScale = v3T;
// Rotate it
transform.rotation = Quaternion.FromToRotation(Vector3.up, v3End-v3Start);
It works fine, with the exception that the resulting cylinders (or "edges") are always longer than the spheres, resulting in this effect:
I would like the cylinder to start and terminate to and from the center of the spheres and not continue further creating this "skewers" effect. I think the solution lies where the cylinders are scaled, however I was not able to fix this. Any hint?
Answer by Gwahir · Oct 25, 2013 at 07:27 PM
Is it possible the starting height of your cylinders is 2? That would result in a doubled length after scaling to the distance between the sphere centers.
If you're using the base cylinder prefab, it's double what you would expect, simply halve the scale on that axis and it should do it for you
@Gwahir is right. You need to take into account the world height of the cylinders. The built-in cylinders have a height of 2.0. You need:
v3T.y = (v3End-v3Start).magnitude / 2.0;