Hello Unity community!
I’ve been doing graphic design for a while but I’ve only started coding/scripting for the first time a couple of days ago. I’m watching some tutorials on how to create a 2D sidescroller but have been adding my own twists here and there with bits I pick up online.
Currently I’m having an issue where my character keeps jumping when the jump key is pressed, but I only wanted him to jump once per press. I looked around online and heard about the if (Input.GetButtonDown(“Jump”)); line of code which should fix it. I tried implementing it but it doesn’t seem to work. I’m guessing my lack of experience with coding format is letting me down, how exactly do I correctly incorporate this into the code below? Simply adding it under void update did nothing, is something else contradicting it? I don’t get any errors…it just doesn’t work.
I’ve put my entire script without the attempt to add this line of code below. Any assistance would be much appreciated. Thank you very much and apologies for the simple question!
public class PlayerController : MonoBehaviour {
// movement variables
public float maxSpeed;
// Jumping Variables
private bool grounded = false;
private float groundCheckRadius = 0.2f;
public LayerMask groundLayer;
public Transform groundCheck;
public float jumpHeight;
Rigidbody2D myRB;
Animator myAnim;
// Use this for initialization
void Start () {
myRB = GetComponent<Rigidbody2D> ();
myAnim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update (){
if (grounded && Input.GetAxis ("Jump") > 0) {
grounded = false;
myAnim.SetBool("isGrounded",grounded);
myRB.AddForce(new Vector2(0,jumpHeight));
}
}
void FixedUpdate () {
// Check if we are grounded - if no, then we are falling
grounded = Physics2D.OverlapCircle (groundCheck.position,groundCheckRadius,groundLayer);
myAnim.SetBool("isGrounded",grounded);
myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
float move = Input.GetAxis ("Horizontal");
myAnim.SetFloat ("speed", Mathf.Abs (move));
myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);
myAnim.SetFloat ("direction", Input.GetAxisRaw ("Horizontal"));
}
}