104 lines
2.9 KiB
C#
104 lines
2.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class DistanceMeasurement : MonoBehaviour
|
|
{
|
|
public bool isPathCanBePlanned = false;//是否可以规划路径
|
|
public LineRenderer lineRenderer; // 用于绘制路径的线段渲染器
|
|
public Transform[] markers; // 存储所有标记点的数组
|
|
public GameObject PosPrefab;
|
|
public UnmannedAerialVehicleManage unmannedAerialVehicleManage;
|
|
void Start()
|
|
{
|
|
lineRenderer.positionCount = 0;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (isPathCanBePlanned)
|
|
{
|
|
if (Input.GetMouseButtonDown(0)&& !IsPointerOverUI())
|
|
{
|
|
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
|
RaycastHit hit;
|
|
if (Physics.Raycast(ray, out hit))
|
|
{
|
|
AddMarker(hit.point);
|
|
}
|
|
}
|
|
if (Input.GetMouseButtonDown(1) && !IsPointerOverUI())
|
|
{
|
|
ClearMarkers();
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
bool IsPointerOverUI()
|
|
{
|
|
// 检测当前鼠标位置是否在UI上
|
|
return UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject();
|
|
}
|
|
|
|
void AddMarker(Vector3 position)
|
|
{
|
|
// 创建一个新的游戏对象作为标记点
|
|
GameObject go = Instantiate(PosPrefab);
|
|
go.transform.position = position;
|
|
|
|
// 将新的标记点添加到数组中
|
|
if (markers == null)
|
|
{
|
|
markers = new Transform[] { go.transform };
|
|
}
|
|
else
|
|
{
|
|
Transform[] newMarkers = new Transform[markers.Length + 1];
|
|
markers.CopyTo(newMarkers, 0);
|
|
newMarkers[markers.Length] = go.transform;
|
|
markers = newMarkers;
|
|
unmannedAerialVehicleManage.positions.Enqueue(go.transform.position);
|
|
go.transform.SetParent(transform);
|
|
}
|
|
|
|
// 根据新的标记点数组重新绘制路径
|
|
DrawPath();
|
|
}
|
|
|
|
void DrawPath()
|
|
{
|
|
if (markers.Length < 2)
|
|
{
|
|
return; // 如果标记点不足两个,则不绘制路径
|
|
}
|
|
|
|
// 将所有路径点存储到列表中
|
|
List<Vector3> pathPoints = new List<Vector3>();
|
|
for (int i = 0; i < markers.Length; i++)
|
|
{
|
|
pathPoints.Add(markers[i].position);
|
|
}
|
|
|
|
// 绘制路径
|
|
lineRenderer.positionCount = pathPoints.Count;
|
|
lineRenderer.SetPositions(pathPoints.ToArray());
|
|
}
|
|
|
|
void ClearMarkers()
|
|
{
|
|
if (markers != null)
|
|
{
|
|
Transform[] newmarkers = new Transform[1];
|
|
newmarkers[0] = markers[0];
|
|
for (int i=1;i< markers.Length; i++)
|
|
{
|
|
Destroy(markers[i].gameObject);
|
|
}
|
|
markers = newmarkers;
|
|
lineRenderer.positionCount = 0;
|
|
unmannedAerialVehicleManage.positions.Clear();
|
|
}
|
|
}
|
|
}
|