【发布时间】:2019-07-28 21:38:46
【问题描述】:
我正在统一 c# 中制作一个脚本,它需要加速或减速玩家,以便他顺利地朝着一个方向移动。我有点让它工作了,但它最终有一些我无法修复的缺陷。
我需要的确切行为是: 一个vector3速度值,每帧增加一个加速度值,朝向vector3方向。
需要识别何时减速,然后用减速值代替加速值减速。
它需要以速度为目标,因此它不会加速超过该速度,如果该速度在移动时发生变化,它需要减速/加速到新的速度。
正如我所说,我尝试制作它,但卡住了,这是我使用的代码:
private void Move()
{
if (targetDirection.x > 0)
{
currentSpeedX = Mathf.Min(currentSpeedX + acceleration, targetSpeed);
}
else if (currentSpeedX > 0)
{
currentSpeedX = Mathf.Max(currentSpeedX - decceleration, 0f);
}
if (targetDirection.x < 0)
{
currentSpeedX = Mathf.Max(currentSpeedX - acceleration, -targetSpeed);
}
else if (currentSpeedX < 0)
{
currentSpeedX = Mathf.Min(currentSpeedX + decceleration, 0f);
}
if (targetDirection.z > 0)
{
currentSpeedZ = Mathf.Min(currentSpeedZ + acceleration, targetSpeed);
}
else if (currentSpeedZ > 0)
{
currentSpeedZ = Mathf.Max(currentSpeedZ - decceleration, 0f);
}
if (targetDirection.z < 0)
{
currentSpeedZ = Mathf.Max(currentSpeedZ - acceleration, -targetSpeed);
}
else if (currentSpeedZ < 0)
{
currentSpeedZ = Mathf.Min(currentSpeedZ + decceleration, 0f);
}
Vector3 moveDirection = new Vector3(currentSpeedX, 0, currentSpeedZ);
currentSpeedX = Mathf.Clamp(moveDirection.x, -Mathf.Abs(moveDirection.normalized.x), Mathf.Abs(moveDirection.normalized.x));
currentSpeedZ = Mathf.Clamp(moveDirection.z, -Mathf.Abs(moveDirection.normalized.z), Mathf.Abs(moveDirection.normalized.z));
rb.MovePosition(rb.position + new Vector3(currentSpeedX, 0f, currentSpeedZ) * targetSpeed * Time.fixedDeltaTime);
}
我最终遇到的问题是:
它被锁定到 8 个方向。 在移动到较低速度时更改速度限制,加速而不是减速。
所以,如果有人能帮助我理解为什么这段代码不起作用,或者给我另一种解决这个问题的方法,我将不胜感激。
【问题讨论】: