Unity简单的通过鼠标点击移动

public class PlayerController : MonoBehaviour
{

    CharacterController cc;

    [SerializeField]
    float m_RotationSpeed = 10f;

    [SerializeField]
    private float speed = 10;

    Quaternion m_TargetDir;

    Vector3 targetPos = Vector3.zero;
    bool isRotated = false;





    void Start()
    {
        cc = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitinfo;
            if (Physics.Raycast(ray, out hitinfo))
            {
                if (hitinfo.transform.CompareTag("Ground"))
                {
                    targetPos = hitinfo.point;
                    isRotated = false;
                    m_RotationSpeed = 0; //对旋转速度初始,因为下边对这个值叠加了.
                    Debug.DrawLine(Camera.main.transform.position, hitinfo.point, Color.red, 10);
                }
            }
        }
        if (!cc.isGrounded)
        {
            cc.Move((transform.position + new Vector3(0, -1000, 0)) - transform.position);
        }


        if (targetPos != Vector3.zero)
        {
            if (Vector3.Distance(targetPos, transform.position) > 0.1f)
            {

                Vector3 dir = (targetPos - transform.position).normalized;
                dir *= Time.deltaTime * speed;
                dir.y = 0; //免得脸朝地

                if (!isRotated)
                {
                    m_RotationSpeed += 5; //逐加旋转速度
                    m_TargetDir = Quaternion.LookRotation(dir);
                    transform.rotation = Quaternion.Lerp(transform.rotation, m_TargetDir, m_RotationSpeed * Time.deltaTime);
                    if (Quaternion.Angle(transform.rotation, m_TargetDir) < 1f)
                    {
                        m_RotationSpeed = 1;
                        isRotated = true;
                    }
                }

                cc.Move(dir);
            }
        }
    }
}

 

Unity简单的通过鼠标点击移动

上一篇:LeetCode 448. Find All Numbers Disappeared in an Array & 442. Find All Duplicates in an Array


下一篇:数据分析:构建可视化报表服务