我試圖檢測剛體中的 y 速度,以確定玩家是否可以跳躍。出于某種原因,我從 rb.velocity[2] 獲得的組件與我在控制臺中記錄 rb.velocity 時看到的不匹配。一些幫助理解如何從剛體獲得垂直速度分量會非常有幫助。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody rb;
public Vector3 xvector = new Vector3 (1, 0, 0);
public Vector3 yvector = new Vector3 (0, 1, 0);
public float strafeforce = 1f ;
public float jumpforce = 15f;
// Update is called once per frame
void Update()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (Input.GetKey("right") )
{
rb.AddForce(strafeforce, 0, 0, ForceMode.Impulse) ;
}
if (Input.GetKey("left") )
{
rb.AddForce(-strafeforce, 0, 0, ForceMode.Impulse) ;
}
if (Input.GetKey("up") )
{
rb = GetComponent<Rigidbody>();
if (rb.velocity[2] == 0)
{
rb.AddForce(0, jumpforce, 0, ForceMode.Impulse) ;
}
Debug.Log(rb.velocity);
Debug.Log(rb.velocity[2]);
}
}
}
所以問題是由于某種原因,來自 rb.velocity 的第二個值與我從 rb.velocity[2] 得到的值不匹配。
uj5u.com熱心網友回復:
在 C# 中,索引從 0 開始。這意味著索引 2 實際上是向量的第三個分量(即 z 速度)。如果你想要第二個組件,你應該實際使用rb.velocity[1].
但是,如果您想獲得特定分量,例如 y 速度,則可以改用rb.velocity.x,rb.velocity.y和rb.velocity.z。這使代碼更易于閱讀,因為您可以一目了然地看到您嘗試訪問的軸。
uj5u.com熱心網友回復:
由于實作不同,差異只存在于Log中ToString。
Unity 的默認格式用于Vector3.ToString將F1所有值四舍五入為單個小數的用途
public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) format = "F1"; return UnityString.Format("({0}, {1}, {2})", x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider)); }
默認情況下不是這種情況float.ToString。
你想確保它們在日志中匹配,例如
Debug.Log(rb.velocity.ToString("G9"));
Debug.Log(rb.velocity[2].ToString("G9"));
或者實際上只是
Debug.Log(rb.velocity.z.ToString("G9"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347444.html
