Unity 计算输入方向和相机方向,使对象旋转到目标方向

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

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

简单测试

直接上代码

using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class RotateTest : MonoBehaviour
{
    public Vector2 inputMove; 
    public bool toTargetFlag;
    public bool addCameraEuler;//是否加上相机的旋转角
    public float _tospeed = 5f;//旋转速度
    public float eulerAngle;//监视物体的欧拉角
    [Header("rotate calculate")]
    float _targetRotation;//目标旋转角

    Transform cam;

    void Start()
    {
        cam = Camera.main.transform; 
    }

    void Update()
    {
        if (inputMove != Vector2.zero)
        {
            inputMove.Normalize();
            //计算输入的角度
            _targetRotation = Mathf.Atan2(inputMove.x, inputMove.y) * Mathf.Rad2Deg;
            if (addCameraEuler)
            {
                _targetRotation += cam.transform.eulerAngles.y; //只需要实现输入旋转时 屏蔽掉这行 , 
            }
        }

        if (inputMove != Vector2.zero && !toTargetFlag)
        {
            toTargetFlag = true;
            StartCoroutine(Rote());
        }

        eulerAngle = transform.eulerAngles.y;
    }
    IEnumerator Rote()
    {
        Quaternion cache = Quaternion.Euler(0, _targetRotation, 0);//需要到达的旋转方向
        while (transform.eulerAngles.y != cache.eulerAngles.y )
        {
            transform.rotation = Quaternion.RotateTowards(transform.rotation, cache, _tospeed);
            yield return null;
        }
        toTargetFlag = false;
        Debug.Log("我到达旋转的方向了");
        yield return null;
    }

    public void Move_performed(InputAction.CallbackContext obj)
    {
        //使用的是inputsystem的回调 ,换成 旧的input.getaxis("veritcal") ,input.getaxis("horizontal") 也行
        inputMove = obj.ReadValue<Vector2>();
    }


}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值