0

I had my code working perfectly the character was moving side to side and jumping but I tried to get him to stop jumping twice and he just stopped moving entirely. Can you help me figure out what I did wrong? I have looked this question up but yet to find an answer that makes sense to me (I'm relatively new) so if some can work through this with me I would appreciate it greatly so I can get back to work learning.

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

public class Player : MonoBehaviour

{
  bool jumpKeyWasPressed;
  float horizontalInput;
  Rigidbody rigidBodyComponent;
  bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        rigidBodyComponent = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
    //Space key input
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyWasPressed = true;   
        }

        horizontalInput = Input.GetAxis("Horizontal");
    }

    //main problem I think
    void FixedUpdate ()
    {
            if (!isGrounded)
        {
            return;
        }

        if (jumpKeyWasPressed)
        {
            rigidBodyComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }

        rigidBodyComponent.velocity = new Vector3(horizontalInput,rigidBodyComponent.velocity.y, 0);
    }
 
    void OnCollisionEnter(Collision collision)
    {
        isGrounded = true;
    }

    void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
    }
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Here's a [quick primer on C# vs C++](https://www.educba.com/c-plus-plus-vs-c-sharp/) and [Visual Studio vs Visual Studio Code](https://stackoverflow.com/questions/30527522/what-are-the-differences-between-visual-studio-code-and-visual-studio). Note that the utility you use to edit your code (be it Visual Studio or Visual Studio Code) is not responsible for executing your code, therefore these should not be tagged unless you are specifically asking about either of these two applications. Please be careful not to misuse tags in future. – ProgrammingLlama Jan 04 '21 at 06:20
  • And be sure not to deliberately misuse tags to get more attention for your question (the attention garnered from such an approach is rarely positive). – ProgrammingLlama Jan 04 '21 at 06:23
  • sorry I actually didn't realize I was using the wrong tags I thought C++ and C# were the same thing. – Quentin C Jan 04 '21 at 18:29

1 Answers1

0

If isGrounded is false, you return right out of the function. The last line is also skipped this way. To fix this, you could simply check if isGrounded is true, and only execute the jumping code then (forget return).

if (isGrounded) {
    if (jumpKeyWasPressed) {
        // ...
    }
}
CoderCharmander
  • 1,862
  • 10
  • 18