所以我目前正在用C#制作游戏,我通过按住左移键增加了冲刺的能力,但问题是我不希望玩家在蹲伏时能够冲刺,而这可能发生在只要同时按住左移键和左控制键即可。我已经尝试过“ GetButtonUp”和“ GetButtonDown”,但是它们根本不起作用。这是我当前遇到问题的Sprint脚本:
public class AdvancedMovement : MonoBehaviour
{
//Variables;
PlayerMovement basicMovementScript;
public float speedBoost = 10f;
// Start is called before the first frame update
void Start()
{
basicMovementScript = GetComponent<PlayerMovement>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
beginSprint();
else if (Input.GetKeyUp(KeyCode.LeftShift))
endSprint();
}
private void beginSprint()
{
basicMovementScript.speed += speedBoost;
}
private void endSprint()
{
basicMovementScript.speed -= speedBoost;
}
}
非常感谢您的帮助。谢谢。
[Input.GetKeyDown
和Input.GetKeyUp
仅被调用一次,那是在执行动作并渲染下一帧时。
如果由于性能或调试原因而跳过特定帧,可能会导致意外行为。在您的情况下,可能会转换为调用endSprint
而没有检测到Input.GetKeyDown(KeyCode.LeftShift)
作为示例。
我建议您改用Input.GetKey
,每次按住该键时都会在每次更新时调用它。
根据您的情况,您可以这样做:
if (Input.GetKeyDown(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol))
,将确保不按住向左Ctrl键。
我在类似情况下也将执行的操作,而不是使用Input.GetKeyDown(KeyCode.LeftShift)
,我将创建一个标志_isSprinting
并以类似于以下方式的方式使用它:
void Update()
{
if (!_isSprinting && Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.Leftcontrol)))
{
beginSprint();
_isSprinting = true;
}
if (_isSprinting && !Input.GetKey(KeyCode.LeftShift))
{
endSprint();
_isSprinting = false;
}
}