Unity3d中LookRotation详解
首先来解释一下LookRotation的作用是什么。
这个函数的计算返回值是一个旋转值,表示物体的姿态,这个姿态是使得一个物体看向另一个物体的旋转姿态。
这个函数需要两个参数:Vector3:forward,Vector3:upward。Forward就是指的最终物体自身前向坐标轴的朝向,Upward就是指的最终物体的顶部坐标轴的朝向。通过这两个向量来计算最终物体右边坐标轴的朝向.
右边方向的计算
在说明怎么计算之前,先说一下Vector3.Cross(lhs,rhs)这个函数返回的向量的方向。
我们都知道叉积的结果的方向用右手定则来判断,那么这个函数应该怎么使用右手定则呢?
通过实验后发现,Vector3.Cross(lhs,rhs)是得到rhs x lhs的结果,使用右手定则,让四指朝向rhs,向lhs弯曲,拇指的方向就是最后结果的方向.
那么通过实验就可以发现,最终物体右边方向是可以通过Vector3.Cross(forward,upward)来得出结果的
下面是测试代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rot : MonoBehaviour {
public Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 forw = target.position-transform.position;
Vector3 right = Vector3.Cross (transform.up,forw);
Debug.DrawLine (transform.position, transform.position+transform.up*10,Color.red); //绘制上曲线
Debug.DrawLine (transform.position, target.position,Color.red); //绘制前向曲线
Debug.DrawLine(transform.position,transform.position+right*10,Color.blue); //绘制旋转轴
Quaternion rot = Quaternion.LookRotation(forw,transform.up);
transform.rotation = rot;
}
}
实验结果
Author:寒江雪
Date:2018.1.18