- Home /
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
Answer by robertbu · Apr 23, 2014 at 09:40 AM
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. $$anonymous$$aybe because i try to write it in c# ??? ins$$anonymous$$d of var sphere I use public Transform sphere1 and ins$$anonymous$$d of var dir = Sphere2.position - Sphere1.position; i use Vector3 dir = ...
is it ok ??
Here is a C# translation of the code. Before integrating it into your app, test it in a new scene. In a new scene, create two spheres and a cylinder. Attach the script to a cylinder and initialize 'Sphere1' and 'Sphere2' through drag and drop. Wile running, move the spheres around.
using UnityEngine;
using System.Collections;
public class Bug25b : $$anonymous$$onoBehaviour {
public Transform sphere1;
public Transform sphere2;
void Start() {
transform.localScale = new Vector3 (0.25f, 1.0f, 0.25f);
}
void Update() {
Vector3 dir = sphere2.position - sphere1.position;
transform.position = sphere1.position + 0.5f * dir;
Vector3 scale = transform.localScale;
scale.y = dir.magnitude * 0.5f;
transform.localScale = scale;
transform.rotation = Quaternion.FromToRotation(Vector3.up, dir);
}
}