How to make a cylinder follow two sphere

Hi, i’m new and i’m trying to make a simple project in unity.
I have 3 object : a cylinder, and two spheres. I’d like to make the cylinder follow the two sphere like a sort of line through two point.
Any suggestions ?? I’ve tried to use the Quaternion.LookRotation() and the Quaternion.FromToRotation() functions but it didn’t works.

thanks

Can you elaborate a more about how you want cylinder to follow? with an illustration maybe?

This is the illustration : there are the red sphere and the blue one connected by the cylinder. In the project i can move the red and the blue sphere in the 3d space and i want that the gray cylinder always connect the spheres. thanks [25614-immagine.png|25614]

1 Answer

1

Here is a bit of code to get you started:

#pragma strict
 
 var sphere1 : Transform;
 var sphere2 : Transform;
 
function Start() {
	transform.localScale = Vector3 (0.25, 1.0, 0.25);
}

function Update() {
	var dir = sphere2.position - sphere1.position;
	transform.position = sphere1.position + 0.5 * dir;
	transform.localScale.y = dir.magnitude * 0.5;
	transform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
}

You have to initialize Sphere1 and Sphere2 in the Inspector by drag and drop. Start() set the x and z to 0.25 as the width of the cylinder. Set as appropriate to your application.

thanks, but i can't use that code. There are some errors. Maybe because i try to write it in c# ??? instead of var sphere I use public Transform sphere1 and instead of var dir = Sphere2.position - Sphere1.position; i use Vector3 dir = ... is it ok ??

thank you !! it works !! :)