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

迈不过友情╰ 2022-04-15 03:07 579阅读 0赞

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

  1. // Use this for initialization
  2. void Start () {
  3. Rigid = GetComponent<Rigidbody>();
  4. }
  5. // Update is called once per frame
  6. void Update () {
  7. // if (Input.GetKeyDown(KeyCode.Space))
  8. // {
  9. // Rigid.AddForce(Vector3.up*10000f);
  10. // Rigid.velocity = new Vector3(0,5,0);
  11. // }
  12. // Rigid.AddForce(Vector3.zero);
  13. // Rigid.velocity = Vector3.zero;
  14. if (PlayerAnimator.Instance.State != PlayerState.Dead)
  15. {
  16. // 获取用户按键
  17. float h = Input.GetAxis("Horizontal");
  18. float v = Input.GetAxis("Vertical");
  19. if (h != 0 || v != 0)
  20. {
  21. PlayerAnimator.Instance.ChangeStateMove();
  22. }else if((h == 0 || v == 0) && Cor == null)
  23. {
  24. PlayerAnimator.Instance.ChangeStateIdle();
  25. }
  26. // 移动
  27. transform.Translate(new Vector3(h, 0, v) * Speed * Time.deltaTime, Space.Self);
  28. // transform.Translate(new Vector3(h, 0, v) * Speed * Time.deltaTime,Space.World);
  29. // 刚体移动
  30. // Vector3 postion = Rigid.position + new Vector3(h, 0, v) * Speed * Time.deltaTime;
  31. // Rigid.MovePosition(postion);
  32. // 制作一条射线
  33. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  34. RaycastHit hitInfo;
  35. // 鼠标移动
  36. if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hitInfo, 100f, CanRay))
  37. {
  38. if (Cor != null)
  39. {
  40. StopCoroutine(Cor);
  41. }
  42. Cor = StartCoroutine("Move", hitInfo);
  43. }
  44. // 人物旋转
  45. if (Physics.Raycast(ray, out hitInfo, 100f, CanRay))
  46. {
  47. // print(hitInfo.collider.name);
  48. // 防止射线碰在地面上,导致主角低头
  49. Vector3 point = hitInfo.point;
  50. point.y = transform.position.y;
  51. transform.LookAt(point);
  52. // Quaternion.LookRotation(hit.point-transform.position);
  53. }
  54. }
  55. }
  56. // 移动的携程
  57. IEnumerator Move(RaycastHit hitInfo)
  58. {
  59. PlayerAnimator.Instance.ChangeStateMove();
  60. while (transform.position != hitInfo.point)
  61. {
  62. transform.position = Vector3.MoveTowards(transform.position, hitInfo.point, 0.05f);
  63. yield return 0;
  64. }
  65. Cor = null;
  66. }

}

发表评论

表情:
评论列表 (有 0 条评论,579人围观)

还没有评论,来说两句吧...

相关阅读

    相关 unity3D人物移动实现(二)

    运行之前的项目,小人可以自由移动,但是移动过程中,会有停止按键后滑动一段距离的效果,这是因为脚本中的GetAxis函数,他得到的值随着按键的过程而变化,所以每一次松开的时候,该

    相关 unity3D 射线检测

    在开发中,尤其是跟模型与交互的时候,都会用到射线检测,这篇文章给大家分享一些射线检测的方法实现。 射线:射线是3D世界中一个点向一个方向发射的一条无终点的线,在发射轨迹中与其