Unity实现第三人称角色控制

摄像机的控制:(挂载在摄像机的第一个父物体上)

public class CameraCtrl : MonoBehaviour

{
    public GameObject rotateY;
    public GameObject rotateX;


    private Quaternion targetTransY;
    private Quaternion targetTransX;


    private float mouseY;
    private float mouseX;


    private float YAngleChange;
    private float XAngleChange;


    private float smoothSpeed = 10f;


    void LateUpdate()
    {
        //if (Input.GetMouseButton(0))
        //{
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");


        RotateByX(mouseY);
        RotateByY(mouseX);
        //}
    }
    void RotateByY(float xValue)
    {
        YAngleChange += xValue * smoothSpeed * Time.deltaTime * 90;
        targetTransY = Quaternion.Euler(0, YAngleChange, 0);
        rotateY.transform.localRotation = Quaternion.Slerp(rotateY.transform.localRotation, targetTransY, 2);


    }
    void RotateByX(float yValue)
    {
        XAngleChange -= yValue * smoothSpeed * Time.deltaTime * 90;
        XAngleChange = Mathf.Clamp(XAngleChange, -70f, 40f);
        targetTransX = Quaternion.Euler(XAngleChange, 0, 0);
        rotateX.transform.localRotation = Quaternion.Slerp(rotateX.transform.localRotation, targetTransX, 2);

    }

}


人物控制:(挂载在人物身上)

public class MoveCtrl : MonoBehaviour
{
    private Vector3 offset;


    public GameObject mainCameraFa;


    public Camera mainCamera;


    private float smooth = 5f;
    private float speed = 5f;


    void Start()
    {
        offset = mainCameraFa.transform.position - transform.position;
    }


    void Update()
    {
        mainCameraFa.transform.position = Vector3.Lerp(mainCameraFa.transform.position, transform.position + offset, Time.deltaTime * smooth);

// Vector3.ProjectOnPlane( Vector3 vector,Vector3 planeNormal)
//得到投影向量 为vector到以planeNormal为法向量的平面上。

        Vector3 forward = Vector3.ProjectOnPlane(mainCamera.transform.forward, Vector3.up).normalized;
        Vector3 right = Vector3.ProjectOnPlane(mainCamera.transform.right, Vector3.up).normalized;


        if (Input.GetKey(KeyCode.W))
        {
            transform.position += forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.position -= forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.position += right * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.A))
        {
            transform.position -= right * speed * Time.deltaTime;
        }
    }
}


你可能感兴趣的:(Unity仿真开发)