unity3D中物体移动与相机跟随

时间:2025-04-01 08:58:37
using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading; using UnityEngine; public class camerlook : MonoBehaviour { public float MouseSpeed; public Transform player; private float xmove; // Start is called before the first frame update void Start() { //锁定鼠标位置,防止乱跑而造成奇怪的视角 Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void Update() { //创建鼠标(摄像机)移动 float x, y; //X上的位移等于鼠标X移动速度乘时间 x = Input.GetAxis("Mouse X") * MouseSpeed * Time.deltaTime; y = Input.GetAxis("Mouse Y") * MouseSpeed * Time.deltaTime; xmove = xmove - y; //对x方向移动进行限幅,感兴趣可以试试注释掉是什么现象(斜眼笑) xmove = Mathf.Clamp(xmove, -90, 90); this.transform.localRotation = Quaternion.Euler(xmove, 0, 0); //创建三维向量 player.Rotate(Vector3.up * x); } }