[英]Can not get precise positioning of Rigidbody in Unity3D
我正在创建一个与标准略有不同的 3D 无尽跑步者。 有 1 个单位宽的 5 条车道,如果它们向左或向右移动太远,玩家可能会从两侧掉下来。 玩家不会向前移动、跳跃或滑动。 它只有向左或向右移动。 如果玩家被迎面而来且速度随时间增加的障碍物击中,玩家可能会向后弹起。
关于玩家的左/右移动,我非常接近。 但是我无法准确定位播放器。
有时,当玩家越过一条车道时,位置有时会偏离 0.1,并且可能会随着时间的推移开始堆积。 即从 0 位置开始,向左移动,它在 0.9 或 1.1 处停止。
这是到目前为止的代码 -
{
public float speed;
public float mleft = -0.7f;
public float mright = 0.7f;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKeyDown("a"))
{
rb.velocity = new Vector3(mleft, 0, 0) * speed;
StartCoroutine(stopLaneCH());
}
Debug.Log(GetComponent<Transform>().position);
if (Input.GetKeyDown("d"))
{
rb.velocity = new Vector3(mright, 0, 0) * speed;
StartCoroutine(stopLaneCH());
}
}
IEnumerator stopLaneCH ()
{
yield return new WaitForSeconds(0.5f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
}
我不得不尝试在速度和使玩家移动 1 个单位的mleft/mright变量之间找到平衡。
我对 Unity 和编程还是很陌生,但是非常感谢您对这个问题的任何帮助。
我什至可以用任何帮助解决这个问题的人来命名我的第三个孩子。
如果我理解正确,而不是改变速度,因为要让它精确移动 1 个单位几乎是不可能的。 相反,为什么不将玩家精确移动一个单位呢? 使用协程,您可以使用 Vector3.Lerp 方法随着时间的推移从当前位置移动到所需位置。 您想要的位置是 1 个单位,或者,您的每条车道与您当前位置之间的距离。
void Update(){
//For Moving Left
if (Input.GetKeyDown(KeyCode.A))
StartCoroutine(MoveToPosition(transform, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), 0.5f));
//For Moving Right
if (Input.GetKeyDown(KeyCode.D))
StartCoroutine(MoveToPosition(transform, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), 0.5f));
}
public IEnumerator MoveToPosition(Transform transform, Vector3 position, float timeToMove)
{
var currentPos = transform.position;
var t = 0f;
while (t < 1)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, position, t);
yield return null;
}
}
我假设您在 X 轴上向左/向右移动,如果不是,只需将 - 1 更改为您正在移动的轴。 您也可以根据自己的喜好更改 TimeToMove 浮动。
希望这可以帮助。 如果您有任何问题随时问!
在这里,您可以使用 Time.deltaTime 属性。 速度的值应该是“你想在 1 秒内扫描多少个单位”乘以 2 因为你的协程将在 0.5 秒内停止。
或者,如果您的协程必须在 1.0 秒内停止。 那么速度的值将仅为“您想在 1 秒内渗透多少单位”。
我希望,它对你有帮助!
public float speed;
public float mleft = -0.7f;
public float mright = 0.7f;
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKeyDown("a"))
{
rb.velocity = new Vector3(mleft, 0, 0) * speed * Time.deltaTime;
StartCoroutine(stopLaneCH());
}
Debug.Log(GetComponent<Transform>().position);
if (Input.GetKeyDown("d"))
{
rb.velocity = new Vector3(mright, 0, 0) * speed * Time.deltaTime;
StartCoroutine(stopLaneCH());
}
}
IEnumerator stopLaneCH ()
{
yield return new WaitForSeconds(0.5f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.