A
A
AntiLockYT2020-05-04 17:06:04
Unity
AntiLockYT, 2020-05-04 17:06:04

Unity3D error in 2D platformer script! Why doesn't he jump?

What is the error in the code why the character does not jump??? I press W, but he does not jump! I would be grateful for advice on solving the problem!

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

public class Controller : MonoBehaviour
{
    int speed = 2;
  int jump = 10;
  Rigidbody2D rb;
  bool ground = false;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
    if(ground == true && Input.GetKeyDown(KeyCode.W))
      rb.AddForce(transform.up * jump,ForceMode2D.Impulse);
    }
  
  private void OnCollisionEnter2D(Collision2D collision)
  {
    if(collision.gameObject.tag == "ground")
      ground = true;
  }
  
  private void OnCollisionExit2D(Collision2D collision)
  {
    if(collision.gameObject.tag == "ground")
      ground = false;
  }
  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OblivionGM, 2020-05-04
@AntiLockYT

The first thing you can immediately see is a very poor implementation of checking whether the character is on the ground.
Most likely, your character does not jump because the program does not notice that he is standing on the ground, because of such an implementation. If you made the body (rigidbadi) also kinematic, then you are not surprised at all. Use Physics2D.OverlapCircleAll to check if the character is touching the floor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question