在 Unity 中,你可以使用以下脚本将其挂在摄像机上,以使摄像机在屏幕上下滑动时平移:

using UnityEngine;

public class CameraPan : MonoBehaviour
{
    public float panSpeed = 1f; // 平移速度

    private float startYPosition; // 初始Y位置

    private void Start()
    {
        startYPosition = transform.position.y;
    }

    private void Update()
    {
        // 获取手指触摸或鼠标滚轮滚动的值
        float panInput = 0f;

        if (Input.touchSupported)
        {
            if (Input.touchCount > 0)
            {
                Touch touch = Input.GetTouch(0);
                panInput = touch.deltaPosition.y;
            }
        }
        else
        {
            panInput = Input.mouseScrollDelta.y * -100f; // 乘以-100是为了增加滚动速度
        }

        // 计算新的摄像机位置
        float newYPosition = transform.position.y + (panInput * panSpeed * Time.deltaTime);

        // 限制摄像机移动范围,可根据实际需求调整范围
        newYPosition = Mathf.Clamp(newYPosition, startYPosition - 10f, startYPosition + 10f);

        // 更新摄像机位置
        transform.position = new Vector3(transform.position.x, newYPosition, transform.position.z);
    }
}

将此脚本挂在摄像机上后,你可以根据实际需要调整平移速度(panSpeed)和移动范围限制(startYPosition - 10f 和 startYPosition + 10f)。

Unity 摄像机脚本:屏幕滑动平移相机

原文地址: https://www.cveoy.top/t/topic/pbLt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录