框选

框选物品人物等等
1,需要设置的东西 选择这个模型并且 关闭Fill Center 直接就出现中空矩形,代码写好挂上即可
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxSelection : MonoBehaviour
{
public Camera cam;//获取摄像机
// Start is called before the first frame update
void Start()
{
cam = Camera.main;//此处获取主相机
}
Vector3 startpos;//开始拖拽时候的位置
bool isDrag = false;//是否拖拽
Rect rect;//矩形
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))//按左键
{
startpos = Input.mousePosition;//获取开始拖拽时候鼠标位置
isDrag = true;//设置true
}
if (isDrag)
{
float w = Mathf.Abs(startpos.x - Input.mousePosition.x);//获取开始拖拽与当前位置的差值
float h = Mathf.Abs(startpos.y - Input.mousePosition.y);
GetComponent<RectTransform>().sizeDelta = new Vector2(w, h);//设置当前图片的宽高
float x = startpos.x < Input.mousePosition.x ? startpos.x + w / 2 : Input.mousePosition.x + w / 2;//判断向哪个方向拖拽
float y = startpos.y < Input.mousePosition.y ? startpos.y + h / 2 : Input.mousePosition.y + h / 2;
GetComponent<RectTransform>().anchoredPosition = new Vector2(x - Screen.width / 2, y - Screen.height / 2);//设置锚点位置 用比值
rect = new Rect(x - w / 2, y - h / 2, w, h);
}
if (Input.GetMouseButtonUp(0))
{
GetComponent<RectTransform>().sizeDelta = Vector2.zero;//清零
isDrag = false;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!