Rachel Dockter
Rachel Dockter

Reputation: 986

Input getKeyDown not firing

I'm making a 2d game in Unity. I have a player sprite with this script attached. The right and left keys move perfect but when I try to get the space bar, it doesn't work

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

    public class Player : MonoBehaviour {

        public float moveSpeed;
        public float jumpHeight;

        // Use this for initialization
        void Start () {

        }

        // Update is called once per frame
        void Update () {

            Rigidbody2D playerBody = GetComponent<Rigidbody2D>();

            if (Input.GetKeyDown("space")){
                print("fired");
                //playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
            }

            if (Input.GetKey(KeyCode.LeftArrow))
            {
                playerBody.velocity = new Vector2(-moveSpeed, playerBody.velocity.y);
            }

            if (Input.GetKey(KeyCode.RightArrow))
            {
                playerBody.velocity = new Vector2(moveSpeed, playerBody.velocity.y);
            }
        }
    }

I have also tried Keycode.Space instead of "space" which didn't work either

Also for some reason, I cannot remove or replace the unity3d tag but it's for a 2d unity game.

Upvotes: 2

Views: 1922

Answers (1)

Jarett LeVan
Jarett LeVan

Reputation: 389

Your code appears to be all good, so it may be an error with your console window. Make sure in the top right corner of the console you have the comment box highlighted so anytime you print something in the code, it will appear. Also, I would suggest you use forces to make your character jump instead of velocity. In this case, you said the player's vertical velocity to jumpHeight, but never change it back so your character will constantly be moving upward. You should change that line to:

playerBody.AddForce (transform.up * jumpHeight);

and you may need to adjust the jumpHeight accordingly.

Upvotes: 2

Related Questions