Unity两个物体之间动态生成圆柱

本文介绍了如何在Unity中实现两个动态移动的物体之间,根据它们的位置实时生成连接它们的圆柱体,以展示物体间的动态连接效果。通过C#脚本控制物体位置变化,并利用Unity的图形API在世界空间中绘制圆柱形线条,实现这一功能。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject obj1;
    public GameObject obj2;
    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update ()
    {
        drawCylinder(obj1.transform.position,obj2.transform.position);

    }
    private Dictionary<int, Mesh> _meshMap = new Dictionary<int, Mesh>();
    private void drawCylinder(Vector3 a, Vector3 b)
    {
        float length = (a - b).magnitude;

        Graphics.DrawMesh(getCylinderMesh(length),
            Matrix4x4.TRS(a, Quaternion.LookRotation(b - a), Vector3.one),obj1.GetComponent<MeshRenderer>().material
            ,
            gameObject.layer);
    }//通过obj1.GetComponent<MeshRenderer>().material改圆柱材质
    private Mesh getCylinderMesh(float length)
    {
        int lengthKey = Mathf.RoundToInt(length * 100 / 12);

        Mesh mesh;
        if (_meshMap.TryGetValue(lengthKey, out mesh))
        {
            return mesh;
        }

        mesh = new Mesh();
        mesh.name = "GeneratedCylinder";
        mesh.hideFlags = HideFlags.DontSave;

        List<Vector3> verts = new List<Vector3>();
        List<Color> colors = new List<Color>();
        List<int> tris = new List<int>();

        Vector3 p0 = Vector3.zero;
        Vector3 p1 = Vector3.forward * length;
        for (int i = 0; i < 12; i++)
        {
            float angle = (Mathf.PI * 2.0f * i) / 12;
            float dx = 0.2f * Mathf.Cos(angle);//通过更改0.2数值更改x方向半径
            float dy = 0.2f * Mathf.Sin(angle);//通过更改0.2数值更改y方向半径

            Vector3 spoke = new Vector3(dx, dy, 0);

            verts.Add((p0 + spoke) * transform.lossyScale.x);
            verts.Add((p1 + spoke) * transform.lossyScale.x);

            colors.Add(Color.red);
            colors.Add(Color.red);

            int triStart = verts.Count;
            int triCap = 12 * 2;

            tris.Add((triStart + 0) % triCap);
            tris.Add((triStart + 2) % triCap);
            tris.Add((triStart + 1) % triCap);

            tris.Add((triStart + 2) % triCap);
            tris.Add((triStart + 3) % triCap);
            tris.Add((triStart + 1) % triCap);
        }

        mesh.SetVertices(verts);
        mesh.SetIndices(tris.ToArray(), MeshTopology.Triangles, 0);
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.UploadMeshData(true);

        _meshMap[lengthKey] = mesh;

        return mesh;
    }
}

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值