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.
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;
}
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()
{
}
}