关于unity的鼠标双击和移动触摸屏的双击

鼠标的双击相对比较简单,百度一下可以搜到很多,如下:

function OnGUI(){
	if(Event.current.isMouse && Event.current.type == EventType.MouseDown && Event.current.clickCount == 2){
		print("double click");
	}
}

上面是双击屏幕的事件,假如想双击某个物体呢,就要这样:

private var b = false;
function OnGUI(){
	if(Event.current.isMouse && Event.current.type == EventType.MouseDown && Event.current.clickCount == 2){
		if(b){
			print("double click " + transform.name);
		}
	}
}
function OnMouseEnter(){
	b = true;
}
function OnMouseExit(){
	b =false;
}
意思就是,当鼠标进入你想点击的物体后,双击才有效果,否则鼠标未进入物体,或者exit时,b = false,双击无效果。


下面是移动设备上触屏的双击:

private var t1:double;
private var t2:double;
function Update(){
	if(Input.GetMouseButtonDown(0)){
		t2 = Time.realtimeSinceStartup;
		if(t2 - t1 < 0.2){
			print("double click");
		}
		t1 = t2;
	}
}
我在一篇博客看到过移动端GetMouseButtonDown是有效果的,所以这样利用t1,t2,记录两次单击的时间间隔,假如小于0.2s,则被判断为双击。

同样,移动端点击某一确定物体的双击事件,把下面脚本赋给要点击的物体,

private var t1:double;
private var t2:double;
public var cam:Camera;
function Update(){
	if(Input.GetMouseButtonDown(0)){
		var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
		var hit:RaycastHit;
		if(Physics.Raycast(ray,hit)){
			if(hit.transform.name == gameObject.transform.name){
				t2 = Time.realtimeSinceStartup;
				if(t2 - t1 < 0.2){
					print("double click " + transform.name);
				}
				t1 = t2;
			}
		}
	}
}

对于t1和t2可以定义为System.DateTime类型,这样t2 = System.DateTime.Now;相减后用TimeSpan.如下:

private var t1:System.DateTime;
private var t2:System.DateTime;
public var cam:Camera;
function Update(){
	if(Input.GetMouseButtonDown(0)){
		var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
		var hit:RaycastHit;
		if(Physics.Raycast(ray,hit)){
			if(hit.transform.name == gameObject.transform.name){
				t2 = System.DateTime.Now;
				if(t2 - t1 < System.TimeSpan(0,0,0,0,200)){
					print("double click " + transform.name);
				}
				t1 = t2;
			}
		}
	}
}

最后是,关于GUI的双击,原理都类似:

private var b = false;
private var t = 0.0;
function OnGUI(){
	if(GUI.Button(Rect(10,10,80,50),"click me")){
		t = Time.time;
		if(b){
			print("it's doublic click");
			b = false;
		}else{
			b = true;
		}
	}
}

function FixedUpdate(){
	if(t + 0.2 < Time.time){
		b = false;
	}
}

你可能感兴趣的:(原创)