码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2018-07-18 15:13:24      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:form   +=   scree   .com   getdir   简单   distance   raycast   normal   

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简单的通过鼠标点击移动

标签:form   +=   scree   .com   getdir   简单   distance   raycast   normal   

原文地址:https://www.cnblogs.com/what-lee/p/9329096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!