鼠标拖动的同时绘制一块同等大小的区域:如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 通过鼠标框选绘制矩形区域
/// </summary>
/// public enum MouseType
{left = 0,right = 1,middle = 2
}
public class DrawRectangleArea : MonoBehaviour
{bool _canAddArea = true;/// <summary>/// 是否可以绘制/// </summary>public bool canAddArea{set { _canAddArea = value; }get { return _canAddArea; }}bool _isDraw = false;[SerializeField]Transform areaCube;Vector3 leftTopPos = Vector3.zero;Vector3 rightBottomPos = Vector3.zero;/// <summary>/// 绘制区域所在的层级/// </summary>[SerializeField]LayerMask maskLayer = 0;/// <summary>/// 设置鼠标哪个按键绘制/// </summary>[SerializeField]MouseType _mouseType = MouseType.right;public MouseType mouseType { set { _mouseType = value; } }void AddArea(){if (_canAddArea){if (Input.GetMouseButtonDown((int)_mouseType)){// 从相机位置发射一条射线经过屏幕上的鼠标点击位置Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// 声明一个射线碰撞信息类RaycastHit hit;// 进行碰撞检测 if (Physics.Raycast(ray, out hit, Mathf.Infinity, maskLayer, QueryTriggerInteraction.Ignore)){_isDraw = true;leftTopPos = hit.point;}}if (Input.GetMouseButton((int)_mouseType)){if (_isDraw){// 从相机位置发射一条射线经过屏幕上的鼠标点击位置Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// 声明一个射线碰撞信息类RaycastHit hit;// 进行碰撞检测if (Physics.Raycast(ray, out hit, Mathf.Infinity, maskLayer, QueryTriggerInteraction.Ignore)){rightBottomPos = hit.point;Vector3 offset = leftTopPos + rightBottomPos;Vector3 scale = rightBottomPos - leftTopPos;areaCube.position = new Vector3(offset.x * 0.5f, leftTopPos.y + 0.5f, offset.z * 0.5f);areaCube.localScale = new Vector3(Mathf.Abs(scale.x), 1, Mathf.Abs(scale.z));}}}if (Input.GetMouseButtonUp((int)_mouseType)){_isDraw = false;}}}// Update is called once per framevoid Update(){AddArea();}
}