- Home /
Create cylinder primitive between 2 endpoints?
I'm playing a bit with reading model coordinates from a text file, and wondering how one would instantiate a cylinder primitive (arbitrary radius) between 2 fixed endpoints, x1,y1,z1 and x2,y2,z2.
Just wondering if anyone has an efficient quick way to do it.
Answer by Mike 3 · Jul 01, 2010 at 01:41 AM
This takes a default unity cylinder (must be added as a prefab) and stretches it out between two points, with a specified width. If you change it to a different cylinder, the scale may need to be manipulated slightly (right now it's divided by two as the default cylinder is 2m tall):
var cylinderPrefab : GameObject; //assumed to be 1m x 1m x 2m default unity cylinder to make calculations easy
//added the start function for testing purposes function Start() { CreateCylinderBetweenPoints(Vector3.zero, new Vector3(10, 10, 10), 0.5); }
function CreateCylinderBetweenPoints(start : Vector3, end : Vector3, width : float) { var offset = end - start; var scale = new Vector3(width, offset.magnitude / 2.0, width); var position = start + (offset / 2.0);
var cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity);
cylinder.transform.up = offset;
cylinder.transform.localScale = scale;
}
Why the "Quaternion.identity" doesn't take effecT? It's not 0,0,0...
It's there as a filler. The next line is used to set the rotation properly
ook, anyways, I upgraded my code, what do u think? lol urs is better :@
To anyone following this via a Google search, I wonder if perhaps GameObject.CreatePrimitive isn't maybe a more suitable way to do this without a prefab..?
Answer by doukasd · Dec 11, 2012 at 06:09 AM
Have a look at the source of this module, it creates a procedural cylinder. You might be able to easily make it create it from A to B.
Answer by andrewluck · Oct 01, 2019 at 10:50 AM
Here's the working modified code for newer versions of Unity/C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class point2point : MonoBehaviour
{
public Rigidbody cylinderPrefab; //assumed to be 1m x 1m x 2m default unity cylinder to make calculations easy
// Start is called before the first frame update
void Start()
{
CreateCylinderBetweenPoints(Vector3.zero, new Vector3(10, 10, 10), 0.5f);
}
void CreateCylinderBetweenPoints(Vector3 start, Vector3 end, float width)
{
var offset = end - start;
var scale = new Vector3(width, offset.magnitude / 2.0f, width);
var position = start + (offset / 2.0f);
var cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity);
cylinder.transform.up = offset;
cylinder.transform.localScale = scale;
}
// Update is called once per frame
void Update()
{
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613063543im_/https://answers.unity.com/themes/thub/images/avi.jpg)