using Cinemachine; using System.Collections; using System.Collections.Generic; using UnityEngine; public class WorkerMove1 : MonoBehaviour { private CharacterController chara; public float MoveSpeed = 4f; public CinemachineFreeLook freeLook; private float Gravity = -9.8f; private float yVelocity = 0f; public Transform Foot; // Start is called before the first frame update void Start() { chara = GetComponent(); //Cursor.visible = false; //Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void Update() { if (Input.GetKey(KeyCode.LeftShift)) { MoveSpeed = 8f; } else { MoveSpeed = 4f; } if (IsGround()) { yVelocity = 0f; } else { yVelocity += Gravity * Time.deltaTime; } chara.Move(new Vector3(0f, yVelocity, 0f) * Time.deltaTime); KeyControl(); } private void KeyControl() { Vector3 cameraWorldPos = freeLook.transform.position; // 2. 获取Look At目标的世界位置(FreeLook的LookAt属性) Vector3 lookAtWorldPos = freeLook.LookAt.position; // 3. 计算相机看向目标的世界方向(归一化,仅保留方向) Vector3 lookAtWorldDir = (lookAtWorldPos - cameraWorldPos).normalized; float x = lookAtWorldDir.x; float z = lookAtWorldDir.z; Vector3 xyz = new Vector3(x, 0, z).normalized; float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 forwardMove = xyz * vertical; Vector3 rightMove = transform.right * horizontal; Vector3 move = forwardMove + rightMove; Vector3 realMove = move.normalized * MoveSpeed * Time.deltaTime; chara.Move(realMove); if (move.sqrMagnitude > 0f) { Quaternion targetRotation = Quaternion.LookRotation(xyz); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f); } } bool IsGround() { return Physics.CheckSphere(Foot.position, 0.01f); } }