My character can't jump/Mi personaje no puede saltar

When I press “w” my character don’t jump, I tagged the platform and I used the “private void OnCollisionEnter2D(Collision2D collision)”, this is the script:/ Cuando presiono “w” my pesonaje no salta, yo “taggie” la plataforma y use “private void OnCollisionEnter2D(Collision2D collision)” este es el codigo:

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

public class MovimientoI : MonoBehaviour
{
    bool canJump = true;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Izquierda
        if (Input.GetKey("a"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-200f * Time.deltaTime, 0));
        }
        // Izquierda, más veloz
        if (Input.GetKey("a") && Input.GetKey(KeyCode.RightShift))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(-600f * Time.deltaTime, 0));
        }
        // Derecha
        if (Input.GetKey("d"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(200f * Time.deltaTime, 0));
        }
        // Derecha, más veloz
        if (Input.GetKey("d") && Input.GetKey(KeyCode.RightShift))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(600f * Time.deltaTime, 0));
        }
        if (Input.GetKeyDown("w") && canJump)
        {
            canJump = false;
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 200f));
        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.tag == "platform")
        {
            canJump = true;
        }
    }
}

Y-hello there,

the culprit is in the OnCollisionEnter2D, the right call is collision.gameObject.tag == "platform" not transform.

Also for future reference, calling GetComponent each time is a waste of resources, instead you can create a Rigidbody2D variable and referencing it in the Awake() or Start() methods like:

Rigidbody2D myBody;
void Awake()
{
   if(myBody == null)
      myBody = gameObject.GetComponent<Rigidbody2D>();
}

and then you can just call:

myBody.AddForce(new Vector2(-200f * Time.deltaTime, 0));

Hope this helps :slight_smile:

1 Like

Thank you, I had not payed attention to that mistake.

No problem :smile:

Weirdly enough Unity does not throw an error if you use transform.tag