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

Posted what-lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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简单的通过鼠标点击移动的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D基础让物体动起来②--UGUI鼠标点击逐帧移动

Unity —— 通过鼠标点击控制物体移动

unity3鼠标点击移动

Unity 物体跟随鼠标点击移动,判断物体是否在移动

unity 鼠标点击一个物体后再点击另一个物体

unity3d里照相机跟随鼠标左右移动的代码怎么写