当前位置:   article > 正文

Unity 计算输入方向和相机方向,使对象旋转到目标方向_unity输入转化为局部朝向

unity输入转化为局部朝向

问题案例,当需要播放翻滚动画的,先要旋转当前对象,而旋转的方向,就取决于我们的输入方向和相机的方向,然后再播放翻滚的动画.

当然也可以用作普通的输入方向和相机方向,将对象向着指定的方向进行移动,这样的话 _targetRotation 是直接进行使用,而不是用协程缓存的方式了.

简单测试

直接上代码

  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.InputSystem;
  4. public class RotateTest : MonoBehaviour
  5. {
  6. public Vector2 inputMove;
  7. public bool toTargetFlag;
  8. public bool addCameraEuler;//是否加上相机的旋转角
  9. public float _tospeed = 5f;//旋转速度
  10. public float eulerAngle;//监视物体的欧拉角
  11. [Header("rotate calculate")]
  12. float _targetRotation;//目标旋转角
  13. Transform cam;
  14. void Start()
  15. {
  16. cam = Camera.main.transform;
  17. }
  18. void Update()
  19. {
  20. if (inputMove != Vector2.zero)
  21. {
  22. inputMove.Normalize();
  23. //计算输入的角度
  24. _targetRotation = Mathf.Atan2(inputMove.x, inputMove.y) * Mathf.Rad2Deg;
  25. if (addCameraEuler)
  26. {
  27. _targetRotation += cam.transform.eulerAngles.y; //只需要实现输入旋转时 屏蔽掉这行 ,
  28. }
  29. }
  30. if (inputMove != Vector2.zero && !toTargetFlag)
  31. {
  32. toTargetFlag = true;
  33. StartCoroutine(Rote());
  34. }
  35. eulerAngle = transform.eulerAngles.y;
  36. }
  37. IEnumerator Rote()
  38. {
  39. Quaternion cache = Quaternion.Euler(0, _targetRotation, 0);//需要到达的旋转方向
  40. while (transform.eulerAngles.y != cache.eulerAngles.y )
  41. {
  42. transform.rotation = Quaternion.RotateTowards(transform.rotation, cache, _tospeed);
  43. yield return null;
  44. }
  45. toTargetFlag = false;
  46. Debug.Log("我到达旋转的方向了");
  47. yield return null;
  48. }
  49. public void Move_performed(InputAction.CallbackContext obj)
  50. {
  51. //使用的是inputsystem的回调 ,换成 旧的input.getaxis("veritcal") ,input.getaxis("horizontal") 也行
  52. inputMove = obj.ReadValue<Vector2>();
  53. }
  54. }

其实这是很基础的东西了 - -!,希望对你能有帮助.

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

闽ICP备14008679号