public class EasyTouch : MonoBehaviour {
//拖动的图片
public GameObject touch;
//起始点
Vector3 origin;
//供外部调用的返回向量
public Vector3 Dir { get; set; }
void Start () {
UUIEventListener.Get(touch).onDown += OnDown;
UUIEventListener.Get(touch).onUp += OnUp;
origin = touch.transform.position;
}
private void OnUp(GameObject go) {
isDrag = false;
touch.transform.position = origin;
}
bool isDrag = false;
private void OnDown(GameObject go) {
isDrag = true;
}
float x = 0;
float y = 0;
void Update () {
if (isDrag) {
x = Input.mousePosition.x;
y = Input.mousePosition.y;
//限制拖动物体的移动范围
x = Mathf.Clamp(x, origin.x - 100, origin.x + 100);
y = Mathf.Clamp(y, origin.y - 100, origin.y + 100);
touch.transform.position = new Vector3(x, y, 0);
//返回当前拖动结果
Dir = touch.transform.position - origin;
}
}
}
本文介绍了一个Unity脚本,用于实现游戏中的图片拖动功能,并限制了拖动的范围,确保图片不会超出预设的边界。脚本通过监听鼠标事件来开始和结束拖动,同时使用Clamp函数限制拖动的位置。
4056

被折叠的 条评论
为什么被折叠?



