Unity使用叉乘实现LookAt看向功能

直接上代码:
叉乘实现: 判断左右 能做到看向

void Update()
    {
        a = transform.forward;
        b = (target.position - transform.position).normalized;
        Vector3 crossValue = Vector3.Cross(a, b);
        Debug.Log(crossValue);
        if (crossValue.y >= 0)
        {
            transform.Rotate(Vector3.up, 0.5f);
        }
        if (crossValue.y < 0)
        {
            transform.Rotate(Vector3.up, -0.5f);
        }
    }

点乘实现, 判断前后 能做到forward与target所在方位垂直.

void Update()
    {
        a = transform.forward.normalized;
        b = (target.position - transform.position).normalized;
        float dotValue = Vector3.Dot(a, b);
        //float angle = Mathf.Acos(dotValue) * Mathf.Rad2Deg;
        Debug.Log(dotValue);
        if (dotValue > 0)
        {
            transform.Rotate(Vector3.up, 0.5f);
        }
        if (dotValue < 0)
        {
            transform.Rotate(Vector3.up, -0.5f);
        }
    }

使用joystick进行移动。
法1:

/// <summary>
    /// 1.求出forwad的夹角 2.旋转向量
    /// </summary>
    /// <param name="v2"></param>
    /// <returns></returns>
    private void MoveAlongWithHead(Vector2 axis, float speed = 1f)
    {
        Vector3 cross = Vector3.Cross(transform.forward, head.forward);
        float angle = Vector3.Angle(transform.forward, head.forward);
        angle = cross.y < 0 ? -angle : angle;
        Vector3 dir = Quaternion.Euler(0, angle, 0) * new Vector3(axis.x, 0, axis.y).normalized;
        rb.MovePosition(transform.position + dir * speed * Time.fixedDeltaTime);
    }

法2:

    private void MoveAlongWithHead(Vector2 axis, float stepLength)
    {
        Vector3 headLookAt = head.forward;
        Vector3 headLookAtNormalized = Vector3.ProjectOnPlane(headLookAt, new Vector3(0, 1, 0));
        headLookAtNormalized = headLookAtNormalized.normalized;
        Vector3 axis3D = (new Vector3(axis.x, 0, axis.y)).normalized;
        Quaternion q = Quaternion.LookRotation(headLookAtNormalized);
        axis3D = q * axis3D;
        transform.position = transform.position + axis3D * stepLength * Time.fixedDeltaTime;
        //Debug.DrawLine(head.transform.position, head.transform.position + axis3D * 10, Color.red);
    }

eg:Quaternion实现lookat, v3(自己) - v3(target)

transform.rotation = Quaternion.LookRotation(transform.position - Camera.main.transform.position);

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值