当前位置:   article > 正文

Unity 第一人称视角控制移动、旋转_unity如何实现流畅转动视角

unity如何实现流畅转动视角

第一人称视角操作

此功能主要是借鉴YouTube上一个博主的教程,写的蛮好我就搬运过来让大家也试试。

1、控制对象与镜头是子父级关系

2、控制器对象添加CharacterController,Rigidbody组件如下:

3、重头戏:创建PlayerController脚本并比此脚本挂到控制器上

其原理是:左右旋转是控制父物体的欧拉角的Y轴

 transform.Rotate(0, Input.GetAxis("Mouse X") * sensetivity,0);

上下点头是子物体相机的欧拉角Z轴

 playerCamera.Rotate(-Input.GetAxis("Mouse Y") * sensetivity, 0, 0);

水平方向

  1. moveDirection = new Vector3(Input.GetAxis("Horizontal")*moveSpeed, moveDirection.y, Input.GetAxis("Vertical")*moveSpeed);
  2. moveDirection = transform.TransformDirection(moveDirection);

跳跃:

  1. if (controller.isGrounded)
  2. {
  3. if (Input.GetButton("Jump"))
  4. moveDirection.y = jumpForce;
  5. else
  6. moveDirection.y = 0;
  7. }

移动

  1. moveDirection.y -= gravity * Time.deltaTime;
  2. controller.Move(moveDirection*Time.deltaTime);

4、源代码奉上:

  1. using UnityEngine;
  2. public class PlayerController : MonoBehaviour
  3. {
  4. [SerializeField] private float moveSpeed = 6f;
  5. [SerializeField] private float jumpForce = 10;
  6. [SerializeField] private float gravity = 15f;
  7. private Vector3 moveDirection;
  8. [Header("Camera details")]
  9. public float sensetivity = 1f;
  10. private Transform playerCamera;
  11. private CharacterController controller;
  12. void Start()
  13. {
  14. controller = GetComponent<CharacterController>();
  15. playerCamera = GetComponentInChildren<Camera>().transform;
  16. Cursor.lockState = CursorLockMode.Locked;
  17. Cursor.visible = false;
  18. }
  19. void Update()
  20. {
  21. transform.Rotate(0, Input.GetAxis("Mouse X") * sensetivity,0);
  22. playerCamera.Rotate(-Input.GetAxis("Mouse Y") * sensetivity, 0, 0);
  23. if (playerCamera.localRotation.eulerAngles.y != 0)
  24. playerCamera.Rotate(Input.GetAxis("Mouse Y")*sensetivity,0,0);
  25. moveDirection = new Vector3(Input.GetAxis("Horizontal")*moveSpeed, moveDirection.y, Input.GetAxis("Vertical")*moveSpeed);
  26. moveDirection = transform.TransformDirection(moveDirection);
  27. if (controller.isGrounded)
  28. {
  29. if (Input.GetButton("Jump"))
  30. moveDirection.y = jumpForce;
  31. else
  32. moveDirection.y = 0;
  33. }
  34. moveDirection.y -= gravity * Time.deltaTime;
  35. controller.Move(moveDirection*Time.deltaTime);
  36. }
  37. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/522686
推荐阅读
相关标签
  

闽ICP备14008679号