框选物品人物等等
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;
}
}
}
标签:mousePosition,float,Input,isDrag,框选,startpos,拖拽 From: https://www.cnblogs.com/qinhuanghan5/p/17203898.html