In Unity, how do I reference the SpaceBar Key in order to apply force to an object when Space Bar is pressed?
void Update()
{
rb.AddForce(0, 0, forwardforce * Time.deltaTime);
if (Input.GetKey("a"))
{
rb.AddForce(500 * Time.deltaTime, 0, 0);
}
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, -500 * Time.deltaTime);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, 500 * Time.deltaTime);
}
if (Input.GetKey("d"))
{
rb.AddForce(-500 * Time.deltaTime, 0, 0);
}
if (Input.GetKey("vbKeySpace"))
{
rb.AddForce(0, 300 * Time.deltaTime, 0);
}
}
You could try the following:
Input.GetKey("space");
Or, using the KeyCode enumeration:
Input.GetKey(KeyCode.Space);
See the docs on this enumeration here.
Input.GetKey operates on the string-names of the Conventional Game Input key list.
Special keys: “backspace”, “tab”, “return”, “escape”, “space”, “delete”, “enter”, “insert”, “home”, “end”, “page up”, “page down”
However, I recommend looking into Input.GetButton instead. This allows the player to rebind the keys to something more suitable for them, rather than being forced to use WASD and Space.
So you would instead use Input.GetButton("Jump") and define in Edit -> Project Settings -> Input that "Jump" is mapped to the positive key "space" (Unity will auto-supply some default keys, and Jump:Space is one).
Additionally you can switch your Input.GetKey("a")/Input.GetKey("d") with Input.GetAxis("Horizontal").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With