Version: 2021.3

Quaternion.SetFromToRotation

切换到手册
public void SetFromToRotation (Vector3 fromDirection, Vector3 toDirection);

描述

创建一个从 fromDirection 旋转到 toDirection 的旋转。

用于创建一个旋转,该旋转从第一个 Vector (fromDirection) 开始,旋转到第二个 Vector (toDirection)。必须在脚本中设置这些 Vector。

//This example shows how the rotation works between two GameObjects. Attach this to a GameObject.
//Make sure to assign the GameObject you would like your GameObject to rotate towards in the Inspector

using UnityEngine;

public class SetFromToRotationExample : MonoBehaviour { //This is the Transform of the second GameObject public Transform m_NextPoint; Quaternion m_MyQuaternion; float m_Speed = 1.0f;

void Start() { m_MyQuaternion = new Quaternion(); }

void Update() { //Set the Quaternion rotation from the GameObject's position to the next GameObject's position m_MyQuaternion.SetFromToRotation(transform.position, m_NextPoint.position); //Move the GameObject towards the second GameObject transform.position = Vector3.Lerp(transform.position, m_NextPoint.position, m_Speed * Time.deltaTime); //Rotate the GameObject towards the second GameObject transform.rotation = m_MyQuaternion * transform.rotation; } }
//In this example your GameObject rotates towards the position of the mouse

using UnityEngine;

public class Example2 : MonoBehaviour { Quaternion m_MyQuaternion; float m_Speed = 1.0f; Vector3 m_MousePosition;

void Start() { m_MyQuaternion = new Quaternion(); }

void Update() { //Fetch the mouse's position m_MousePosition = Input.mousePosition; //Fix how far into the Scene the mouse should be m_MousePosition.z = 50.0f; //Transform the mouse position into world space m_MousePosition = Camera.main.ScreenToWorldPoint(m_MousePosition);

//Set the Quaternion rotation from the GameObject's position to the mouse position m_MyQuaternion.SetFromToRotation(transform.position, m_MousePosition); //Move the GameObject towards the mouse position transform.position = Vector3.Lerp(transform.position, m_MousePosition, m_Speed * Time.deltaTime); //Rotate the GameObject towards the mouse position transform.rotation = m_MyQuaternion * transform.rotation; } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961