借鉴网上的框选物体代码,重新编写了一个框选物体代码。
鼠标按下时,记录第一点位置,鼠标抬起时,记录第二点位置,同时判断物体集合中物体的屏幕坐标是否在两点内。如果在两点内,加入框选物体集合,如果不在两点内,从框选物体集合中移除。
void Update()
{
if(Input.GetMouseButtonDown(0)){
start = Input.mousePosition;//记录第一个点的位置
//将之前选择的物体全部释放
gameObjects.Clear();
}
if(Input.GetMouseButtonUp(0)){
end = Input.mousePosition;//记录第二个点的位置
SelectPeople(start,end);
}
}
//判断每个物体是否在鼠标框选的范围内
private void SelectPeople(Vector3 start, Vector3 end){
if(start != end){
Vector3 p1 = Vector3.zero;
Vector3 p2 = Vector3.zero;
if(start.x > end.x)
{
p1.x = end.x;
p2.x = start.x;
}
else
{
p1.x = start.x;
p2.x = end.x;
}
if(start.y > end.y)
{
p1.y = end.y;
p2.y = start.y;
}
else
{
p1.y = start.y;
p2.y = end.y;
}
//p1在左下,p2在右上
for(int i = 0;i<peopleList.Count;i++){
Vector3 worldPos = ((GameObject)peopleList[i]).transform.position;
Vector3 sceenPos = Camera.main.WorldToScreenPoint(worldPos);
if((sceenPos.x > p1.x && sceenPos.x < p2.x && sceenPos.y > p1.y && sceenPos.y < p2.y))
{
//加入集合中
gameObjects.Add(peopleList[i]);
}
else{
//从集合中移除
gameObjects.Remove(peopleList[i]);
}
}
}
}