[英]C# Unity GetKeyDown() not being detected properly
因此,我准備了一些雪橇原型。 我目前正在編寫一些控件,以補充我已應用的RigidBody物理原理。 我的目標是在向左或向右轉的相反方向施加力,以獲得某種打滑,邊緣捕捉效果,然后向前施加力以補償動量損失。
但是,我無法做到這一點,因為無論出於何種原因,我都無法使GetKeyDown()或GetKeyUp()函數正常工作。 我已包含以下代碼。 基本上發生的是“釋放按鈕”。 文本會不斷輸出,然后偶爾我會得到“按下按鈕”的輸出,該輸出僅發生一次,然后恢復為“釋放按鈕”。 輸出。 即使這樣,也很少見。 通常我沒有任何檢測到的跡象。
我確定我缺少一些微小的東西,並且我一直在尋找類似的問題,但是似乎沒有一個問題能夠解決我的問題。 如果有人可以給我任何想法,我將不勝感激。 同樣,任何優化技巧將不勝感激。 我還是C#和Unity的新手。
我正在進行調整和試驗,因此如果我錯過了一些不必要的評論,我深表歉意。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public bool sidePhysics;
public bool keyPress;
// Use this for initialization
void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 50.0f;
// No vertical controlls for now.
//var z = Input.GetAxis("Vertical") * Time.deltaTime * 40.0f;
// Get axis against which to apply force
var turnAngle = rb.transform.position.x;
transform.Rotate(0, x, 0);
//transform.Translate(0, 0, z);
// Debug to test input detection
keyPress = Input.GetKeyDown(KeyCode.A);
Debug.Log("keyPress: " + keyPress);
// On either right or left key input down, apply force
// Later once keys are being detected - addForce forward too
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D))
{
Debug.Log("Button pressed. ");
// Add opposing force proportionate to the degree of the turn
rb.AddForce((turnAngle * (-x * 10)), 0, 0, ForceMode.Acceleration);
}
else
{
Debug.Log("Button released.");
}
//Debug.Log("RigidBody: " + rb +
// " Rotation: " + x +
// " turnAngle: " + turnAngle);
}
}
如果要在按住鍵的同時連續執行操作,請使用Input.GetKey
函數。 如果您想在按下按鍵時執行一次操作 ,則可以使用Input.GetKeyDown
函數,因為只有在釋放按鍵並再次按下該鍵時,該函數的值為一次。 了解兩者之間的區別很重要。
現在,要檢測何時釋放按鈕,請在檢查Input.GetKey
之后不要使用else
語句。 您不會獲得想要的效果。 要檢測何時釋放按鈕,請使用Input.GetKeyUp
函數。 if
此處添加另一個if
語句。
更像這樣:
if (Input.GetKeyDown(KeyCode.A))
{
//KEY PRESSED
}
if (Input.GetKey(KeyCode.A))
{
//KEY PRESSED AND HELD DOWN
}
if (Input.GetKeyUp(KeyCode.A))
{
//KEY RELEASED
}
最后,您應該始終檢查Update
函數而不是FixedUpdate
函數中的輸入。
除了程序員所說的:
不要在FixedUpdate()
使用GetKeyDown()
(和類似方法FixedUpdate()
一旦鍵更改狀態, GetKeyDown()
僅對單個Update調用返回true。 由於FixedUpdate
是按固定的時間表運行的,因此可能導致錯過(運行得太晚)而無法看到密鑰已更改狀態(因為調用了兩個Update
:一個是true,然后是另一個將其重置為false的Update
。 )。
您需要從Update函數中調用此函數,因為狀態會在每幀中重置
關於拉特的評論[...]關於
GetKey()
我寫了一篇關於GetKeyDown()
仍然是真實的GetKey()
盡管文檔沒有明確說出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.