Unity3d中简单的实现人物移动射线控制人物旋转抬头

// 移动速度
public float Speed = 5f;
// 获取刚体
private Rigidbody Rigid;
// 地面层Layer
public LayerMask CanRay;
// 移动的携程
private Coroutine Cor;

// Use this for initialization
void Start () {
    Rigid = GetComponent();
}

// Update is called once per frame
void Update () {
    // if (Input.GetKeyDown(KeyCode.Space))
    // {
    // Rigid.AddForce(Vector3.up*10000f);
    // Rigid.velocity = new Vector3(0,5,0);
    // }
    // Rigid.AddForce(Vector3.zero);
    // Rigid.velocity = Vector3.zero;

    if (PlayerAnimator.Instance.State != PlayerState.Dead)
    {
        // 获取用户按键
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if (h != 0 || v != 0)
        {
            PlayerAnimator.Instance.ChangeStateMove();
        }else if((h == 0 || v == 0) && Cor == null)
        {
            PlayerAnimator.Instance.ChangeStateIdle();
        }
        // 移动
        transform.Translate(new Vector3(h, 0, v) * Speed * Time.deltaTime, Space.Self);
        // transform.Translate(new Vector3(h, 0, v) * Speed * Time.deltaTime,Space.World);
        // 刚体移动
        // Vector3 postion = Rigid.position + new Vector3(h, 0, v) * Speed * Time.deltaTime;
        // Rigid.MovePosition(postion);

        // 制作一条射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        // 鼠标移动
        if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hitInfo, 100f, CanRay))
        {
            if (Cor != null)
            {
                StopCoroutine(Cor);
            }
            Cor = StartCoroutine("Move", hitInfo);
        }
        // 人物旋转
        if (Physics.Raycast(ray, out hitInfo, 100f, CanRay))
        {
            // print(hitInfo.collider.name);
            // 防止射线碰在地面上,导致主角低头
            Vector3 point = hitInfo.point;
            point.y = transform.position.y;
            transform.LookAt(point);
            // Quaternion.LookRotation(hit.point-transform.position);
        }
    }
}

// 移动的携程
IEnumerator Move(RaycastHit hitInfo)
{
    PlayerAnimator.Instance.ChangeStateMove();
    while (transform.position != hitInfo.point)
    {
        transform.position = Vector3.MoveTowards(transform.position, hitInfo.point, 0.05f);
        yield return 0;
    }
    Cor = null;
}

}

你可能感兴趣的:(人物移动,简单射线实现人物移动)