我正在研究一個測驗專案,以在 Unity 中試驗 Rigidbody。我研究了水平移動和跳躍動作,但我有一個問題。Input.GetKeyDown()大多數時候似乎沒有抓住我的關鍵事件。我試圖尋找該建議在醒目的按鍵輸入可能的解決方案Update(),并與剛體相互作用對應FixedUpdate()。當我嘗試這個時,我發現幾乎沒有改進。這是我現在正在處理的腳本:
public class PlayerScript : MonoBehaviour
{
[SerializeField] private float jumpConstant = 5.0f;
[SerializeField] private int walkSpeed = 10;
private bool jumpDown;
private float horizontalInput;
private Rigidbody rbComponent;
// Start is called before the first frame update
void Start()
{
rbComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CheckIfJumpKeyPressed();
GetHorizontalInput();
}
void FixedUpdate()
{
JumpIfKeyPressed();
MoveHorizontal();
}
void CheckIfJumpKeyPressed()
{
jumpDown = Input.GetKeyDown(KeyCode.Space);
}
void JumpIfKeyPressed()
{
if (jumpDown)
{
jumpDown = false;
rbComponent.AddForce(Vector3.up * jumpConstant, ForceMode.VelocityChange);
Debug.Log("Jumped!");
}
}
void GetHorizontalInput()
{
horizontalInput = Input.GetAxis("Horizontal");
}
void MoveHorizontal()
{
rbComponent.velocity = new Vector3(horizontalInput * walkSpeed, rbComponent.velocity.y, 0);
}
}
先感謝您。
uj5u.com熱心網友回復:
如果您的輸入和物理幀之間出現額外的幀,您將覆寫您的輸入。您應該確保缺少輸入不會覆寫檢測到的輸入:
void CheckIfJumpKeyPressed()
{
jumpDown |= Input.GetKeyDown(KeyCode.Space);
}
或者,等效地:
void CheckIfJumpKeyPressed()
{
if (!jumpDown)
{
jumpDown = Input.GetKeyDown(KeyCode.Space);
}
}
甚至:
void CheckIfJumpKeyPressed()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jumpDown = true;
}
}
無論你覺得哪個最易讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385938.html
上一篇:我的影片沒有在應該播放的時候播放
