版权声明:本文为博主原创文章,未经博主允许不得转载。如有问题,欢迎指正。 https://blog.csdn.net/qq_37352817/article/details/85096677
很多手游里面都有一个滑轮控制人物移动
我前段时间也研究了一下
下面附上源码,因为有注释我就不多说什么了
源码:
public class CoronaScripts : MonoBehaviour {
大圆
private RectTransform bigRect;
小圆
private RectTransform smallRect;
滑轮被激活;默认没有
private bool isActiveTrue = false;
屏幕分辨率比率;这里Canvas是根据宽来缩放的
private float biLv;
用来存储鼠标和大圆的距离;是一个由大圆坐标指向鼠标坐标的方向向量
private Vector3 dis;
void Start () {
bigRect = this.transform.GetChild (0).GetComponent<RectTransform> ();
smallRect = bigRect.transform.GetChild (0).GetComponent<RectTransform> ();
屏幕分辨率的宽除以实际屏幕宽度
biLv = 1280f/ Screen.width;
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
轮盘在屏幕左下角占屏幕1/4的大小范围有效
if (Input.mousePosition.y < Screen.height / 2 && Input.mousePosition.x < Screen.width / 2) {
限制左边和下边的间距,是上面的1/15的长度
if (Input.mousePosition.y > Screen.height / 15 && Input.mousePosition.x > Screen.width / 15) {
滑轮当前状态被激活
isActiveTrue = true;
显示滑轮
bigRect.gameObject.SetActive (true);
生成滑轮大圆的位置在鼠标在实际屏幕的位置
bigRect.anchoredPosition = Input.mousePosition * biLv;
}
}
}
被激活要做的事情;控制小圆的移动
if (isActiveTrue) {
小圆的坐标:等于相对于父物体大圆鼠标的坐标;等于大圆指向鼠标的一个向量;等于鼠标坐标减去大圆坐标;
smallRect.anchoredPosition = Input.mousePosition * biLv - bigRect.anchoredPosition3D;
鼠标到大圆的距离;是一个方向指向鼠标的向量
dis = smallRect.anchoredPosition;
如果鼠标到大圆的距离大于100
if (dis.magnitude > 100) {
将这个向量转换成单位向量乘以一百就是小圆的位置了
dis = smallRect.anchoredPosition.normalized * 100;
smallRect.anchoredPosition = dis;
}
}
if (Input.GetMouseButtonUp (0)) {
isActiveTrue = false;
滑轮隐藏
bigRect.gameObject.SetActive (false);
小圆位置归位
smallRect.anchoredPosition = Vector2.zero;
}
}
}