Unity 控制摄像机镜头的上下左右移动

   

    private float FollowPosx,FollowPosy;
    private float moveAmount=5;   //控制镜头的移动速度

    // Update is called once per frame
    void Update()
    {
        if (Input.mousePosition.y > Screen.height * 0.9)//如果鼠标位置在顶部,就向上移动
        {
            FollowPosy += moveAmount * Time.deltaTime;

        }
        if (Input.mousePosition.y < Screen.height * 0.1)//如果鼠标位置在底部,就向下移动
        {
            FollowPosy -= moveAmount * Time.deltaTime;
        }

        if (Input.mousePosition.x > Screen.width * 0.9)//如果鼠标位置在右侧,就向右移动
        {
            FollowPosx += moveAmount * Time.deltaTime;
        }
        if (Input.mousePosition.x < Screen.width * 0.1) //如果鼠标位置在左侧,就向左移动
        {
            FollowPosx -= moveAmount * Time.deltaTime;
        }

        //调用坐标变换
        Camera.main.transform.position = new Vector3(FollowPosx, FollowPosy, 0);


    }

上述代码检测当鼠标移动到屏幕边缘的时候,摄像头将会往指定的方向移动

Screen.width是获取屏幕的长和宽,通过设置范围来达到指定位置触发移动效果

其中moveAmount控制镜头的移动速度,同时还可以设置moveAmount根据时间发生变化来达到加速或者减速的效果,

Time.deltaTime则是根据帧率来控制镜头的移动速度,帧率越高移动速度越快,反之,越慢.

如果使用Time.fixedDeltaTime则是固定刷新帧率.

猜你喜欢

转载自blog.csdn.net/m0_71650342/article/details/130230754