using UnityEngine;
public class SelectionBox : MonoBehaviour
{
private Vector2 startPos;
private Vector2 endPos;
private bool isDragging = false;
//边界的宽度
public float thickness = 5;
//区域颜色、边界颜色
public Color areaColor = Color.white, borderColor = Color.white;
Rect GetScreenRect(Vector2 start, Vector2 end)
{
// 确保矩形是从左上到右下
float x = Mathf.Min(start.x, end.x), y = Mathf.Max(start.y, end.y);
float width = Mathf.Abs(start.x - end.x), height = Mathf.Abs(start.y - end.y);
return new Rect(x, Screen.height - y, width, height);
}
// 绘制矩形
void DrawScreenRect(Rect rect, Color color)
{
GUI.color = color;
GUI.DrawTexture(rect, Texture2D.whiteTexture);
GUI.color = Color.white;
}
// 绘制矩形边框
void DrawScreenRectBorder(Rect rect, float thickness, Color color)
{
GUI.color = color;
GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, thickness), Texture2D.whiteTexture); // 上
GUI.DrawTexture(new Rect(rect.x, rect.yMax - thickness, rect.width, thickness), Texture2D.whiteTexture); // 下
GUI.DrawTexture(new Rect(rect.x, rect.y, thickness, rect.height), Texture2D.whiteTexture); // 左
GUI.DrawTexture(new Rect(rect.xMax - thickness, rect.y, thickness, rect.height), Texture2D.whiteTexture); // 右
GUI.color = Color.white;
}
public Transform target;
// 获取框选区域内的单位
void SelectUnits()
{
Rect selectionRect = GetScreenRect(startPos, endPos);
Transform target = this.target;
if (target != null)
{
Vector2 screenPos = Camera.main.WorldToScreenPoint(target.position);
target.GetChild(0).gameObject.SetActive(selectionRect.Contains(screenPos));
if (selectionRect.Contains(screenPos))
{
//在区域内
}
else
{
//不在区域内
}
}
}
void OnGUI()
{
if (isDragging)
{
Rect rect = GetScreenRect(startPos, endPos);
DrawScreenRect(rect, areaColor);
DrawScreenRectBorder(rect, thickness, borderColor);
}
}
void Update()
{
// 开始拖拽
if (Input.GetMouseButtonDown(0))
{
startPos = Input.mousePosition;
Debug.Log(startPos);
isDragging = true;
target.GetChild(0).gameObject.SetActive(false);
}
// 结束拖拽
else if (Input.GetMouseButtonUp(0))
{
isDragging = false;
SelectUnits();
}
// 更新当前鼠标位置
if (isDragging)
{
endPos = Input.mousePosition;
}
}
}
Unity选择框(魔兽争霸3)
Jo.H2025-03-28 10:42
相关推荐
向宇it1 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。快乐觉主吖12 小时前
Unity网络通信的插件分享,及TCP粘包分包问题处理erxij2 天前
【游戏引擎之路】登神长阶(十八):3天制作Galgame引擎《Galplayer》——无敌之道心lizz312 天前
GAMES101 lec2-数学基础1(线性代数)啊基米德2 天前
lua(xlua)基础知识点记录一夜色。2 天前
Unity Android Logcat插件 输出日志中文乱码解决X-mj2 天前
Unity URP + XR 自定义 Skybox 在真机变黑问题全解析与解决方案(支持 Pico、Quest 等一体机)erxij2 天前
【游戏引擎之路】登神长阶(十七):Humanoid动画——长风破浪会有时,直挂云帆济沧海erxij2 天前
【游戏引擎之路】登神长阶(十九):3D物理引擎——岁不寒,无以知松柏;事不难,无以知君子心疼你的一切3 天前
Unity 多人游戏框架学习系列一