Home > Back-end >  What is wrong with my c# player jumping code ? (unity 3d)
What is wrong with my c# player jumping code ? (unity 3d)

Time:08-13

I just started learning unity 3d, and I wrote c# code that makes my player jump but it is not working

public Rigidbody rb;
public float SideWaysForce = 500f;
bool CanJump;

    void OnCollisionEnter(Collision collisioninfo)
    {
        if (collisioninfo.collider.tag == "Ground")
        {
            Debug.Log("Can Jump");
            CanJump = true;
        }
        
        if (collisioninfo.collider.tag != "Ground")
        {
            Debug.Log("Can not Jump");
            CanJump = false;
        }
    }

void FixedUpdate()

if (CanJump == true && Input.GetKey("space"))
        {
             rb.AddForce(0, SideWaysForce * Time.deltaTime, 0);
        }

no error messages were shown in the Console

CodePudding user response:

Well, debug (with a debugger or with Debug.Log) if the script even works, then make sure both CanJump and Input.GetKey("Space") are true. Also, you probably should use Input.GetKeyDown if you don't want your character to fly when you're holding a key.

CodePudding user response:

  1. Make sure the player has a rigid body attached
  2. Make sure the player has a Collider attached (eg. mesh collider)
  3. Make sure the player has that script attached.
  4. Make sure the RigidBody (rb) is assigned to the player's rigid body in inspector.
  5. Make sure sideways force is the same value in the inspector and in the code (it should be 500f on both).
  6. In Fixed Update you should have Input.GetKey("Space") not Input.GetKey("space") (I believe the capital letter matters).
  7. Make sure your ground object has the "Ground" tag attached.

If non of these solutions fix your issue please tell me.

  • Related