我正在 Unity (2020.3.40f) 中開發一個 VR 專案,需要添加選項以根據控制器(用戶的手)的移動在其軸上移動物件。
目前我存盤控制器在抓取物體時的位置,并不斷計算控制器從初始位置移動的距離。但這是不準確的,因為控制器可能已朝不應該影響物件位置的方向移動。
例如:
我有這個藍色的杠桿,用戶必須拉。我想知道控制器沿綠色軸移動了多少,所以我可以相應地移動控制桿。
如果用戶向上移動他們的手,它不應該影響杠桿(但在我當前的實作中,我使用Vector3.Distance所以杠桿無論如何都會移動)。

我的代碼:
private void OnTriggerEnter(Collider other)
{
controller = other.GetComponentInParent<IController>();
if (controller == null || controller.IsOccupied)
{
return;
}
controller.IsOccupied = true;
controllerStartPosition = controller.GetPosition();
}
private void Update()
{
if (controller == null) return;
Vector3 currentControllerPosition = controller.GetPosition();
float distance = Vector3.Distance(currentControllerPosition, controllerStartPosition);
transform.Translate(0, 0, distance * sensitivity); // The object always moves along its forward axis.
}
我假設我需要將控制器的位置投影到物件的前軸上并計算其距離,但我對向量數學有非常基本的了解,所以我不確定。
所以我的問題是,為了得到正確的距離,我應該做些什么計算?
uj5u.com熱心網友回復:
如前所述,您要做的是Vector3.Project將給定的手部移動到所需的目標軸方向上,并且僅圍繞該增量移動。
就像是
private void Update()
{
Vetcor3 currentControllerPosition = controller.GetPosition();
// the total vector in world space your hand has moved since start
Vector3 delta = currentControllerPosition - controllerStartPosition;
// the delta projected onto this objects forward vector in world space
// you can of course adjust the vector but from your usage this seems the desired one
Vector3 projectedDelta = Vector3.Project(delta, transform.forward);
// finally moving only about that projected vector in world space
transform.position = projectedDelta * sensitivity;
}
uj5u.com熱心網友回復:
你目前正在做的是;
您正在計算每個軸上的距離,每個軸上的移動都會改變結果。您需要的是在計算距離時僅傳遞所需軸中的引數,例如:
float distance = currentControllerPosition.x - controllerStartPosition.x;
這將為您提供這些點的 x 軸之間的差異。
例如,如果它在 5 并且移動到 8,那么無論在另一個軸上的移動,這都會回傳 3。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528409.html
標籤:C#unity3d数学
