首页 文章

Unity锚定鼠标位置以旋转相机

提问于
浏览
0

我正在尝试创建经典的第三人称效果,您右键单击屏幕并按住旋转相机以查看 . 我想做的是让光标不可见,并将鼠标光标锚定在该点,让相机通过鼠标X /鼠标Y轴旋转 . 我读过以前的帖子声称你不能直接锚定你的鼠标,除非你使用

CursorLockedMode.Locked

但是我不希望我的鼠标跳到屏幕的中心,除非我之后能够将它返回到屏幕上的前一点 . 在这些帖子中,我读过这样做的唯一方法是可能重新创建光标以进行软件控制,然后你可以操纵它的位置,但如果是这种情况我不知道从哪里开始 .

if (rightclicked)
            {
                cursorPosition = currentCursorPosition;
                Cursor.Visible = false;
                //Retrieve MouseX and Mouse Y and rotate camera
            }

基本上,我试图用伪代码完成这个,我读过的所有东西都让人觉得无法实现 .

提前致谢 .

1 回答

  • 2

    你可以试试这个剧本,看看它是否能回答你的问题?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CameraRotateOnRightClick : MonoBehaviour {
        public float angularSpeed = 1.0f;
        public Camera targetCam;
        private Vector3 pivotPointScreen;
        private Vector3 pivotPointWorld;
        private Ray ray;
        private RaycastHit hit;
    
        // Use this for initialization
        void Start () {
            //Set the targetCam here if not assigned from inspector
            if (targetCam == null)
                targetCam = Camera.main;
        }
    
        // Update is called once per frame
        void Update () {
            //When the right mouse button is down,
            //set the pivot point around which the camera will rotate
            //Also hide the cursor
            if (Input.GetMouseButtonDown (1)) {
                //Take the mouse position
                pivotPointScreen = Input.mousePosition;
                //Convert mouse position to ray
                // Then raycast using this ray to check if it hits something in the scene
                //**Converting the mousepositin to world position directly will
                //**return constant value of the camera position as the Z value is always 0
                ray = targetCam.ScreenPointToRay(pivotPointScreen);
                if (Physics.Raycast(ray, out hit))
                {
                    //If it hits something, then we will be using this as the pivot point
                    pivotPointWorld = hit.point;
                }
                //targetCam.transform.LookAt (pivotPointWorld);
                Cursor.visible = false;
            }else if(Input.GetMouseButtonUp(1)){
                Cursor.visible = true;
            }
            if (Input.GetMouseButton (1)) {
                //Rotate the camera X wise
                targetCam.transform.RotateAround(pivotPointWorld,Vector3.up, angularSpeed * Input.GetAxis ("Mouse X"));
                //Rotate the camera Y wise
                targetCam.transform.RotateAround(pivotPointWorld,Vector3.right, angularSpeed * Input.GetAxis ("Mouse Y"));
            }
    
        }
    }
    

相关问题