using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class InputMag : MonoBehaviour
{
private bool isDragging;
private Vector3 startPos;
private Vector3 endPos;
public ImageMag imageMag;
public GameManager gameManager;
private Rect rect;
public float p = 0.02f;
public float max = 5;
public List<GameObject> selectplayers = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ProcessDragRect();
}
private void ProcessDragRect()
{
if (Input.GetMouseButtonDown(0))//当鼠标左键按下
{
isDragging = true;
startPos = Input.mousePosition;
}
if (isDragging)
{
endPos = Input.mousePosition;
Vector3 center = (startPos + endPos) / 2;//计算中心锚点的位置
var size = new Vector3(Mathf.Abs(endPos.x - startPos.x), Mathf.Abs(endPos.y - startPos.y));//
imageMag.SetRectImage(center, size);//设置图片的锚点位置和大小
rect = new Rect(center - size / 2, size);//创建一个UI矩形
}
if (Input.GetMouseButtonUp(0))
{
isDragging = false;
imageMag.HideRectImage();//将框选框隐藏
var allMasters = gameManager.GetAllMasterInfo();//获取场景上所有的玩家对象
foreach (var item in allMasters)
{
item.GetChild(0).gameObject.SetActive(false);//将所有玩家对象身上的选中标记失活
var screenPos = Camera.main.WorldToScreenPoint(item.position);//重新计算玩家对象的坐标
if (rect.Contains(screenPos))//是否存在于屏幕上的框选框范围内
{
Debug.Log(item.name+"在框选范围");
selectplayers.Add(item.gameObject);//将玩家对象添加进选中的集合
item.GetChild(0).gameObject.SetActive(true);//将选中标志激活
}
}
}
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (selectplayers.Count > 0)//当选中的人数大于0
{
float c = 1.2f * selectplayers.Count;
float r = c / (Mathf.PI * 2);
float ang = Mathf.PI * 2 / selectplayers.Count;
for (int i = 0; i < selectplayers.Count; i++)
{
float x = Mathf.Sin(ang * i) * r+hit.point.x;
float z = Mathf.Cos(ang * i) * r+hit.point.z;
float noise = Mathf.PerlinNoise((x + 50) * p, (z + 50) * p);
float y = noise * max;
selectplayers[i].GetComponent<NavMeshAgent>().SetDestination(new Vector3(x, y, z));//让寻路组件移动到计算的位置上
}
}
}
}
}
}