修改图片中心点为鼠标位置,此部分通过鼠标和原中心点距离 与 图片大小的比例来算出中心点要移动的距离,然后根据鼠标和原中心点距离对图片坐标进行改变。
代码:
using UnityEngine;
public class Test: MonoBehaviour {
public void ScrollEvent()
{
float delX = Input.mousePosition.x - transform.position.x;
float delY = Input.mousePosition.y - transform.position.y;
float scaleX = delX / GetComponent<RectTransform>().rect.width / transform.localScale.x;
float scaleY = delY / GetComponent<RectTransform>().rect.height / transform.localScale.y;
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
transform.localScale += Vector3.one * 0.1f;
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
transform.localScale += Vector3.one * -0.1f;
}
GetComponent<RectTransform>().pivot += new Vector2(scaleX, scaleY);
transform.position += new Vector3(delX, delY, 0);
}
}滚轮事件:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ScrollEvent: MonoBehaviour , IScrollHandler
{
public UnityEvent scroll = new UnityEvent();
public void OnScroll(PointerEventData eventData)
{
scroll.Invoke();
}
}
本文介绍了一个Unity脚本,该脚本能够通过鼠标滚轮事件实现图片的缩放,并允许用户通过鼠标点击来调整图片的中心点位置。通过计算鼠标位置与图片原中心点之间的相对距离,脚本可以动态更新图片的位置与缩放级别。
258

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



