作为一个新人,我也来发表一篇文章,大早上的通过unity3d来给大家分享一下我自己做的小demo;
首先获取鼠标在屏幕上点击的那个点的坐标,在这里要用到input类中的MouseButtonDown()这个方法来获得鼠标的左键,右键已经滚轮的点击反应。
今天我们就用左键吧,在MouseButtonDown()这个方法里,使用参数0来表示按下左键,;使用MouseButtonUp(0)方法来表示释放左键,因为在屏幕
中是要拖动的,所以需要持续按下鼠标的函数GetMouseButton(0);这三个函数我们都放在Update里面执行;
在这里我们使用unity自带的画图类库来对鼠标点击并且拖动形成的范围进行画图,我们使用类GL中的一些方法,如PushMatrix()、LoadPixelMatrix(),以及开始画图的点和结束画图的点的函数,在这里就不一一介绍啦,待会直接上传代码就好了。
当鼠标点击拖动,形成的区域肯定是矩形,所以这边涉及上下左右边框的计算,我们使用一个材质来表示,
最后,当鼠标左键施放之后,所形成的区域就在屏幕中释放,我们使用GL中的PopMatrix()函数来表示结束;
下面是我这个demo的源代码,给大家分享一下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetRange : MonoBehaviour {
private Vector2 mouseStartPos, mouseEndPos;
private bool mBDrawMouseRect;
public Material rectMat;//画线的材质
void Start()
{
mBDrawMouseRect = false;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
//按下鼠标左键
{
Vector3 mousePosition = Input.mousePosition;
mouseStartPos = new Vector2(mousePosition.x, mousePosition.y);
}
if (Input.GetMouseButton(0))
//持续按下鼠标左键
{
mBDrawMouseRect = true;
Vector3 mousePosition = Input.mousePosition;
mouseEndPos = new Vector2(mousePosition.x, mousePosition.y);
}
if (Input.GetMouseButtonUp(0))
{
mBDrawMouseRect = false;
}
}
void OnGUI()
{
if (mBDrawMouseRect)
Draw(mouseStartPos, mouseEndPos);
GUILayout.Label("X:"+Input.mousePosition.x);
GUILayout.Label("Y:" + Input.mousePosition.y);
}
//渲染2D框
void Draw(Vector2 start, Vector2 end)
{
rectMat.SetPass(0);
GL.PushMatrix();//保存摄像机变换矩阵
Color clr = Color.green;
clr.a = 0.1f;
GL.LoadPixelMatrix();//设置用屏幕坐标绘图
//透明框
GL.Begin(GL.QUADS);
GL.Color(clr);
GL.Vertex3(start.x, start.y, 0);
GL.Vertex3(end.x, start.y, 0);
GL.Vertex3(end.x, end.y, 0);
GL.Vertex3(start.x, end.y, 0);
GL.End();
//线
//上
GL.Begin(GL.LINES);
GL.Color(Color.green);
GL.Vertex3(start.x, start.y, 0);
GL.Vertex3(end.x, start.y, 0);
GL.End();
//下
GL.Begin(GL.LINES);
GL.Color(Color.green);
GL.Vertex3(start.x, end.y, 0);
GL.Vertex3(end.x, end.y, 0);
GL.End();
//左
GL.Begin(GL.LINES);
GL.Color(Color.green);
GL.Vertex3(start.x, start.y, 0);
GL.Vertex3(start.x, end.y, 0);
GL.End();
//右
GL.Begin(GL.LINES);
GL.Color(Color.green);
GL.Vertex3(end.x, start.y, 0);
GL.Vertex3(end.x, end.y, 0);
GL.End();
GL.PopMatrix();//还原
}
}