如何获得刚体速度的一个分量



我正在尝试检测刚体中的y速度,以确定玩家是否可以跳跃。出于某种原因,当我在控制台中记录rb.velocity时,我从rb.velovity[2]得到的组件与我看到的不匹配。了解如何从刚体获得垂直速度分量将非常有帮助。

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.velovity[2]得到的值不匹配。

在C#中,索引从0开始。这意味着索引2实际上是矢量的第三个分量(即z速度(。如果您想要第二个组件,那么实际上应该使用rb.velocity[1]

但是,如果要获得特定的分量,例如y速度,则可以使用rb.velocity.xrb.velocity.yrb.velocity.z。这使得代码更容易阅读,因为您可以一眼看到您试图访问的轴。

由于不同的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"));

最新更新