其他分享
首页 > 其他分享> > Unity鼠标在屏幕边缘移动视角

Unity鼠标在屏幕边缘移动视角

作者:互联网

效果类似RTS游戏中鼠标在屏幕边缘移动视角

在场景中任意添加一个参照物即可

1.首先是2D场景

新建空物体并搭载脚本CamMove

public class CamMove : MonoBehaviour
{
    public float edgeSize;	//会产生移动效果的边缘宽度
    public float moveAmount;    //移动速度

    public Camera myCamera;	//会移动的摄像机

    private Vector3 camFollowPos;	//用于给摄像机赋值

    private bool edgeScrolling = true;	//移动开关
    // Start is called before the first frame update
    void Start()
    {
        camFollowPos = myCamera.transform.position;	//保存摄像机初始位置,移动是在初始位置的基础上计算
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))	//移动开关
        {
            edgeScrolling = !edgeScrolling;
        }
        if (edgeScrolling)	//如果打开
        {
            //屏幕左下角为坐标(0, 0)
            if (Input.mousePosition.x > Screen.width - edgeSize)//如果鼠标位置在右侧
            {
                camFollowPos.x += moveAmount * Time.deltaTime;//就向右移动
            }
            if (Input.mousePosition.x < edgeSize)
            {
                camFollowPos.x -= moveAmount * Time.deltaTime;
            }
            if (Input.mousePosition.y > Screen.height - edgeSize)
            {
                camFollowPos.y += moveAmount * Time.deltaTime;
            }
            if (Input.mousePosition.y < edgeSize)
            {
                camFollowPos.y -= moveAmount * Time.deltaTime;
            }
            myCamera.transform.position = camFollowPos;//刷新摄像机位置
        }
    }
}

这样鼠标移动到屏幕边缘时摄像头就会移动

2.然后是3D场景

将脚本中会变化的camFollowPos.y改为camFollowPos.z即可

public class CamMove : MonoBehaviour
{
    ......
            if (Input.mousePosition.y > Screen.height - edgeSize)
            {
                camFollowPos.z += moveAmount * Time.deltaTime;
            }
            if (Input.mousePosition.y < edgeSize)
            {
                camFollowPos.z -= moveAmount * Time.deltaTime;
            }
        }
    }
}

标签:moveAmount,视角,鼠标,Unity,camFollowPos,Time,Input,移动,edgeSize
来源: https://www.cnblogs.com/AlphaIcarus/p/16116716.html