Unity Input.GetKeyDown (KeyCode.Space) no detecta la tecla Presione

Aug 30 2020

Estoy aprendiendo Unity pero no se detecta mi pulsación de tecla

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody myBody;

    private float time = 0.0f;
    private bool isMoving = false;
    private bool isJumpPressed = false;

    void Start(){
        myBody = GetComponent<Rigidbody>();
    }
    void Update()
    {
        isJumpPressed = Input.GetKeyDown(KeyCode.Space);
        Debug.Log(isJumpPressed);
    }

    void FixedUpdate(){
        if(isJumpPressed){
            myBody.velocity = new Vector3(0,10,0);
            isMoving = true;
            Debug.Log("jump");
        }
        if(isMoving){
            time = time + Time.fixedDeltaTime;
            if(time>10.0f)
            {
                //Debug.Log( Debug.Log(gameObject.transform.position.y + " : " + time));
                time = 0.0f;
            }
        }
    }

}  

por qué isJumpPressed siempre es falso. ¿Qué estoy haciendo mal? Por lo que entiendo, esto debería funcionar, pero obviamente me falta algo

ACTUALIZACIÓN: Gracias a todos los que propusieron ideas. Conseguí que isJumpPressed volviera verdadero cuando dejé de intentar detectar la barra espaciadora.

isJumpPressed = Input.GetKeyDown("a");

alguien tiene alguna idea de por qué esto funcionaría y no

isJumpPressed = Input.GetKeyDown(KeyCode.Space);

o

isJumpPressed = Input.GetKeyDown("space");

ACTUALIZACIÓN 2: Aparentemente, esto es un error en Linux. He leído que no sucederá cuando el juego se compile solo en el editor. Encontré una solución enhttps://forum.unity.com/threads/space-not-working.946974/?_ga=2.25366461.1247665695.1598713842-86850982.1598713842#post-6188199

Si algún Googler tropieza con este problema, haga referencia al siguiente código porque esto me funciona.

public class Player : MonoBehaviour
{

    public Rigidbody myBody;

    private float time = 0.0f;
    private bool isMoving = false;
    private bool isJumpPressed = false;

    void Start(){
        myBody = GetComponent<Rigidbody>();
    }
    void Update()
    {
        isJumpPressed = Input.GetKeyDown(SpacebarKey());
        if(isJumpPressed)
        {
            Debug.Log(isJumpPressed);
        }
    }

    void FixedUpdate(){
        if(isJumpPressed){
            myBody.velocity = new Vector3(0,10,0);
            isMoving = true;
            Debug.Log("jump");
        }
        if(isMoving){
            time = time + Time.fixedDeltaTime;
            if(time>10.0f)
            {
                //Debug.Log( Debug.Log(gameObject.transform.position.y + " : " + time));
                time = 0.0f;
            }
        }
    }

    public static KeyCode SpacebarKey() {
        if (Application.isEditor) return KeyCode.O;
        else return KeyCode.Space;
    }

} 

Respuestas

2 Pluto Aug 30 2020 at 00:18

El problema es que FixedUpdateya Updateno se llaman uno tras otro. La actualización se llama una vez por cuadro y FixedUpdate se llama una vez por actualización física (el valor predeterminado es 50 actualizaciones por segundo).

Entonces podría suceder lo siguiente:

Update is called -> GetKeyDown is true (this frame only) ->  isJumpPressed = true
Update is called -> GetKeyDown is false ->  isJumpPressed = false
FixedUpdate is called -> isJumpPressed is false 

Aquí hay un ejemplo que imprime "Update Jump" cada vez que presiona la barra espaciadora, y "FixedUpdate Jump" solo algunas veces cuando presiona la barra espaciadora. No hagas esto:

bool isJumpPressed;
void Update()
{
    isJumpPressed = Input.GetKeyDown(KeyCode.Space);
    if (isJumpPressed)
    {            
        Debug.Log("Update Jump");
    }       
}

private void FixedUpdate()
{
    if (isJumpPressed)
    {
        Debug.Log("FixedUpdate Jump");            
    }
}

Haz esto en su lugar:

bool isJumpPressed;
void Update()
{        
    if (Input.GetKeyDown(KeyCode.Space))
    {
        isJumpPressed = true;
        Debug.Log("Update Jump");
    }        
}

private void FixedUpdate()
{
    if (isJumpPressed)
    {
        Debug.Log("FixedUpdate Jump");
        isJumpPressed = false;
    }
}
2 EricPendergast Aug 30 2020 at 01:35

Un posible problema es que su proyecto podría estar usando el nuevo paquete Input System . Si está utilizando este paquete, las antiguas funciones de Input Manager no funcionarán. Para verificar esto, vaya a Edit > Project Settings... > Player > Other Settingsy Active Input Handlingdebe estar configurado en Input Manager (Old)(o Bothtambién podría funcionar).

Si realmente desea usar el paquete Input System, debe instalarlo si aún no lo tiene, y debe verificar si la barra espaciadora está presionada así:

using UnityEngine.InputSystem;

...

jumpPressed = Keyboard.current.space.wasPressedThisFrame;
AthanasiosKataras Aug 29 2020 at 23:04

Consulte los documentos aquí: https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html

Devuelve verdadero durante el marco en el que el usuario comienza a presionar la tecla identificada por su nombre.

Debe llamar a esta función desde la función Actualizar, ya que el estado se restablece en cada cuadro. No volverá a verdadero hasta que el usuario haya soltado la tecla y la haya presionado nuevamente.

Utilice la GetKeyfunción en lugar:https://docs.unity3d.com/ScriptReference/Input.GetKey.html

Devuelve verdadero mientras el usuario mantiene presionada la tecla identificada por su nombre.