- Home /
If Get key not working
Hi. I have this small code that is supposed to let me move left and right and jump, and Unity isn't giving me any errors but when I press the keys the don't work. I'm probably missing something pretty obvious. Anyways here's the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forward = 2000f;
public float sideways = 500f;
public float jump = 100f;
void FixedUpdate () {
rb.AddForce (0, 0, forward * Time.deltaTime);
if ( Input.GetKey ("a") )
{
rb.AddForce (sideways * Time.deltaTime, 0, 0);
}
if (Input.GetKey ("a")) {
rb.AddForce (-sideways * Time.deltaTime, 0, 0);
}
if (Input.GetButtonDown ("Jump")) {
rb.AddForce (0, jump, 0);
}
}
}
Answer by Keftark-Barin · Nov 05, 2020 at 07:11 AM
Hi. You have 2 times GetKey "a" with sideways and -sideways. The second "if" cancels the first. And maybe try "GetKeyDown" instead of "GetButtonDown" for the jump.
Answer by Maggiethegsd · Nov 05, 2020 at 06:00 PM
The first major problem is you have used the a key two times, change the right movement key to D. Also you might wanna try changing GetKey in Jump to GetKeyDown. I also recommend using KeyCodes as an input argument, instead of a string such as "d". You can use like KeyCode.Space, KeyCode.A, etc.
Your answer
Follow this Question
Related Questions
Colliders and GetKey 0 Answers
rotate slowly! 1 Answer
how to move player with getAxis and UI buttons 2 Answers
if Statement Help Increment Value 2 Answers
(if statement) is acting weird 1 Answer