我是靠谱客的博主 悦耳秋天,最近开发中收集的这篇文章主要介绍Unity 判断鼠标上下左右拖动,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

很简单,直接上代码,解释都在注释中。

public class InputController:MonoBehaviour,IPointerDownHandler,IDragHandler,IPointerUpHandler
{
private float fingerActionSensitivity = Screen.width * 0.05f; //手指动作的敏感度,这里设定为 二十分之一的屏幕宽度.
private float fingerBeginX;
private float fingerBeginY;
private float fingerCurrentX;
private float fingerCurrentY;
private float fingerSegmentX;
private float fingerSegmentY;
private int fingerTouchState;
//三种状态
private int state_null = 0;
private int state_touch = 1;
private int state_add = 2;
void Start()
{
fingerBeginX = 0;
fingerBeginY = 0;
fingerCurrentX = 0;
fingerCurrentY = 0;
fingerSegmentX = 0;
fingerSegmentY = 0;
fingerTouchState = state_null;
}
public void OnPointerDown(PointerEventData eventData)
{
if (fingerTouchState == state_null)
{
fingerTouchState = state_touch;
fingerBeginX = Input.mousePosition.x;
fingerBeginY = Input.mousePosition.y;
}
}
public void OnDrag(PointerEventData eventData)
{
if (fingerTouchState != state_touch) return;
fingerCurrentX = Input.mousePosition.x;
fingerCurrentY = Input.mousePosition.y;
fingerSegmentX = fingerCurrentX - fingerBeginX; //计算左右拖动的长度
fingerSegmentY = fingerCurrentY - fingerBeginY; //计算上下拖动的长度
//这边计算你需要拖动的范围才算拖动了
float fingerDistance = fingerSegmentX * fingerSegmentX + fingerSegmentY * fingerSegmentY;
if (fingerDistance > (fingerActionSensitivity * fingerActionSensitivity))
{
ToAddFingerAction();
}
}
public void OnPointerUp(PointerEventData eventData)
{
fingerTouchState = state_null;
}
void ToAddFingerAction()
{
fingerTouchState = state_add;
//判断是左右还是上下,通过设置对立的参数为0进行判断,
if (Mathf.Abs(fingerSegmentX) > Mathf.Abs(fingerSegmentY))
{
fingerSegmentY = 0;
}
else
{
fingerSegmentX = 0;
}
// fingerSegmentX=0 则是上下拖动
if (fingerSegmentX == 0)
{
if (fingerSegmentY > 0)
{
Debug.Log("up");
}
else
{
Debug.Log("down");
}
}
else if (fingerSegmentY == 0)
{
if (fingerSegmentX > 0)
{
Debug.Log("right");
}
else
{
Debug.Log("left");
}
}
}
}

每天进步一点点。

最后

以上就是悦耳秋天为你收集整理的Unity 判断鼠标上下左右拖动的全部内容,希望文章能够帮你解决Unity 判断鼠标上下左右拖动所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部