这里介绍旋转使用四元数的方法
Quaternion.LookRotation(Vector3 dir);
Quaternion.Lerp(Quaternion a, Quaternion b, float t);
首先我们创建一个Unity的脚本,将坐标系用Unity画出来如下
图中白球的位置为0,0,0坐标的原点
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DirTest : MonoBehaviour {
// Update is called once per frame
void Update () {
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Debug.DrawLine(new Vector3 (0, i, j), new Vector3 (10, i, j), Color.red);
Debug.DrawLine(new Vector3 (i, j, 0), new Vector3 (i, j, 10), Color.blue);
Debug.DrawLine(new Vector3 (i, 0, j), new Vector3 (i, 10, j), Color.green);
}
}
}
}
脚本中添加两个Transform p1 ,p2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DirTest : MonoBehaviour {
/// <summary>
///
/// </summary>
public Transform p1;
/// <summary>
///
/// </summary>
public Transform p2;
// Update is called once per frame
void Update () {
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Debug.DrawLine(new Vector3 (0, i, j), new Vector3 (10, i, j), Color.red);
Debug.DrawLine(new Vector3 (i, j, 0), new Vector3 (i, j, 10), Color.blue);
Debug.DrawLine(new Vector3 (i, 0, j), new Vector3 (i, 10, j), Color.green);
}
}
Debug.DrawLine(Vector3.zero, p1.position);
Debug.DrawLine(Vector3.zero, p2.position);
Debug.DrawLine(p1.position,p2.position, Color.black);
Vector3 dir = p1.position - p2.position;
Debug.DrawLine(Vector3.zero,dir, Color.black);
Debug.DrawLine(Vector3.zero,dir, Color.yellow);
}
}
效果如下:
这里我们发现黑线和黄线的方向大小都是一致的只是位置不同而已
这个黄线是有方向的:(0,0,0)到黄线的末端就是向量的方向
创建旋转的物体
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DirTest : MonoBehaviour {
/// <summary>
///
/// </summary>
public Transform p1;
/// <summary>
///
/// </summary>
public Transform p2;
/// <summary>
/// 物体
/// </summary>
public Transform p3;
// Update is called once per frame
void Update () {
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Debug.DrawLine(new Vector3 (0, i, j), new Vector3 (10, i, j), Color.red);
Debug.DrawLine(new Vector3 (i, j, 0), new Vector3 (i, j, 10), Color.blue);
Debug.DrawLine(new Vector3 (i, 0, j), new Vector3 (i, 10, j), Color.green);
}
}
Debug.DrawLine(Vector3.zero, p1.position);
Debug.DrawLine(Vector3.zero, p2.position);
Debug.DrawLine(p1.position,p2.position, Color.black);
Vector3 dir = p1.position - p2.position;
dir.y = 0;
Debug.DrawLine(Vector3.zero,dir, Color.black);
Debug.DrawLine(Vector3.zero,dir, Color.yellow);
Debug.DrawLine(Vector3.zero,dir.normalized, Color.white);
p3.rotation = Quaternion.Lerp(p3.rotation,Quaternion.LookRotation(dir.normalized),Time.deltaTime * 3f);
}
}