框选屏幕中的gameobject,或者点选(处理当场景中的物体可以重叠的时候)屏幕中的gameobject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
public class SelectControl : MonoBehaviour
{
private float3 startPos;
private float3 endPos;
public void OnUpdate()
{
if (Input.GetMouseButtonDown(0))
{
startPos = WorldTouchPos();
}
if (Input.GetMouseButtonUp(0))
{
endPos = WorldTouchPos();
float3 downLeftPos = new float3(math.min(startPos.x, endPos.x), 0, math.min(startPos.z, endPos.z));
float3 upRightPos = new float3(math.max(startPos.x, endPos.x), 0, math.max(startPos.z, endPos.z));
float minDis = 2;
float dis = math.distance(downLeftPos, upRightPos);
int clickNum = dis < minDis ? 1: -1;
if (clickNum > 0)
{
downLeftPos += new float3(-1, 0, -1) * (minDis - dis) * 1f;
upRightPos += new float3(1, 0, 1) * (minDis - dis) * 1f;
}
List<GameObject> allObject = new List<GameObject>();
for(int index =0; index < allObject.Count; index ++)
{
var pos = allObject[index].transform.position;
if (clickNum > 0)
{
if (pos.x >= downLeftPos.x && pos.z >= downLeftPos.z && pos.x <= upRightPos.x && pos.z <= upRightPos.z)
{
clickNum--;
}
}
else if(clickNum == -1)
{
if (pos.x >= downLeftPos.x && pos.z >= downLeftPos.z && pos.x <= upRightPos.x && pos.z <= upRightPos.z)
{
}
}
}
}
}
public static Vector3 WorldTouchPos()
{
return Camera.main.ScreenToWorldPoint(GetTouchPosition());
}
public static Vector3 GetTouchPosition()
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
return Input.mousePosition;
#else
return Input.touches[0].position;
#endif
}
}
|