关于unity中摄像机控制,我总结了一些,希望自己在今后的学习中不会忘记,耶!!!
unity中第一,三人称控制器上绑定的都有一个叫Mouse Look的脚本,我把它写下来了;
[AddComponentMenu("Camera-Control/Mouse Look")] public enum RotationAxes{MouseXAndY=0,Mouse1,MouseY=2} public RotationAxes axes=RotationAxes.MouseXAndY; public float SensitivityX=15F; public float SensitivityY=15F; public float minimumX=-360F; public float maxmumX=360F; public float minimumY=-60F; public float maxmumY=60F; float rotationY=0F; void start() { if(Getcomponent<Rigidbody>()) { GetComponent<Rigidbody>().freezeRotation=true; } } void update() { if(axes==RotationAxes.MouseXAndY) { float rotationX=transform.localEulerAngles.y+Input.GetAxis("Mouse X")*SensitivityX; rotationY+=Input.GetAxis("MouseY")*SensitivityY; rotationY=Mathf.Clamp(rotationY,minimumY,maxmumY); transform.localEulerAngles=new Vector3(-rotationY,rotationX,0); } else if(axes==RotationAxes.MouseX) { transform.Rotate(0,Input.GetAxis("Mouse X")*SensitivityX,0); } else { rotationY+=Input.GetAxis("Mouse Y")*SensitivityY; rotationY=Mathf.Clamp(rotationY,minimumY,maxmumY); transform.localEulerAngles=new Vector3(-rotationY,transform.localEulerAngles.y,0); } }
主角面向鼠标点击的方向:
Vector3 m_pos=Input.mousePosition; //获取鼠标的屏幕坐标; Vector3 p_pos=Camera.main.WorldToScreenPoint(transform.position); //将主角的世界坐标转化为屏幕坐标,为的是获得他的z轴坐标; m_pos.z=p_pos.z; //将主角的屏幕z轴坐标赋值给鼠标; Vector3 wolrd; wolrd.x=Camera.main.ScreenToWorldPoint(m_pos).x; world.z=Camera.main.ScreenToWorldPoint(m_pos).z; world.y=transform.position.y //y轴坐标不变,主角才不会转进地底; transform.LookAt(world); //主角看向鼠标点击的位置;
滑动鼠标中建,调整视野的远近:
float fov=Camera.main.FieldOfView; //获得摄像机调整视野的值; fov+=Input.GetAxis("Mouse ScrollWheel")*sensitivity; //滑动中建,调整视野值得大小; fov=Mathf.Clamp(fov,minFov,maxFov); //限制视野值得大小为(minFov,maxFov); Camera.main.FieldOfView=fov; //再将调整好的值赋值给摄像机的视野;
写的不好,勿喷哦!!
时间: 2024-09-28 19:30:11