Unity点击生成节点连线
- 效果
2.主要代码
Test_Line 控制类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;public class Test_Line : MonoBehaviour
{public GameObject qiu_prefab;public List<GameObject> spheres;public bool istrue = true;public GameObject qr_im;private void Update(){if (Input.GetMouseButtonDown(0) && istrue && !EventSystem.current.IsPointerOverGameObject()){Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit hit;if (Physics.Raycast(ray, out hit)){GameObject obj = hit.collider.gameObject;if (spheres.Count > 2){if (obj == spheres[0]){qr_im.SetActive(true);Debug.Log("是否闭合");}}if (obj.layer != LayerMask.NameToLayer("JieDian")){GameObject jiedian = Instantiate(qiu_prefab, hit.point, new Quaternion());spheres.Add(jiedian);if (spheres.Count > 1){spheres[spheres.Count - 2].GetComponent<DragObjMove>().nextObj = spheres[spheres.Count - 1];spheres[spheres.Count - 2].GetComponent<DragObjMove>().StartTest();}}}}}public void Bihe(){istrue = false;spheres[spheres.Count - 1].GetComponent<DragObjMove>().nextObj = spheres[0];spheres[spheres.Count - 1].GetComponent<DragObjMove>().StartTest();}
}
DragObjMove节点控制类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class DragObjMove : MonoBehaviour
{private Vector3 offset;public GameObject nextObj;private LineRenderer lineRenderer;private Transform startPoint;private Transform endPoint;public Material[] materials;public void StartTest(){if (nextObj != null){startPoint = transform;endPoint = nextObj.transform;lineRenderer = GetComponent<LineRenderer>();lineRenderer.positionCount = 2;}}private void Update(){// 确保起点和终点已赋值且LineRenderer组件存在if (nextObj != null && lineRenderer != null){lineRenderer.SetPosition(0, startPoint.position); // 设置线段的起始位置lineRenderer.SetPosition(1, endPoint.position); // 设置线段的结束位置}}private void OnMouseEnter(){transform.GetComponent<MeshRenderer>().material = materials[1];}private void OnMouseDown(){offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(transform.position).z));}private void OnMouseDrag(){Vector3 newPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(transform.position).z)) + offset;transform.position = newPosition;}private void OnMouseExit(){transform.GetComponent<MeshRenderer>().material = materials[0];}
}
- 资源包下载链接:下载地址
- 补充:导入资源包后,需将节点小球预制体的Layer改成“JieDian”。