废话不多说,先粘贴代码(新建一个脚本,挂载在需要实现功能的物体上即可)
using UnityEngine;
public class RotateAndZoom : MonoBehaviour
{
// 缩放比例限制
private float MinScale = 0.2f;
private float MaxScale = 3.0f;
// 缩放速率
private float scaleRate = 1f;
// 新尺寸
private float newScale;
// 射线
private Ray ray;
private RaycastHit hitInfo;
private bool isDragging = false;
private Vector3 offset;
// 旋转
private float rotationSpeed = 5.0f;
private void Awake()
{
MinScale = gameObject.transform.localScale.x * 0.5f;
MaxScale = gameObject.transform.localScale.x * 3;
scaleRate = gameObject.transform.localScale.x;
}
private void OnMouseDown()
{
isDragging = true;
offset = gameObject.transform.position - GetMouseWorldPosition();
}
private void OnMouseUp()
{
isDragging = false;
}
private void Update()
{
// 拖拽
if (isDragging)
{
Vector3 newPosition = GetMouseWorldPosition() + offset;
transform.position = newPosition;
}
if (Input.GetMouseButton(1))
{
float mousX = Input.GetAxis("Mouse X");
float mousY = Input.GetAxis("Mouse Y");
transform.Rotate(mousY * rotationSpeed, -mousX * rotationSpeed, 0, Space.World);
}
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
newScale += Input.GetAxis("Mouse ScrollWheel") * scaleRate;
newScale = Mathf.Clamp(newScale, MinScale, MaxScale);
transform.localScale = new Vector3(newScale, newScale, newScale);
}
}
private Vector3 GetMouseWorldPosition()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = -Camera.main.transform.position.z;
return Camera.main.ScreenToWorldPoint(mousePos);
}
}
此脚本依据物体原有尺寸进行缩放,泛用性比较强,适用于不同缩放程度的物体,代码中缩放的数值可以根据需要进行修改
我是一只北辰星,不定时分享干货内容~