I am having an issue with my character which is not jumping at all. I am new to Unity, but I made sure to apply the script to the player and adjust the speed, I did not touch the Rigidbody 2D. If any one can help me figure our the issue, it will be much appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
public float jumpSpeed;
public bool grounded = false;
private Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update () {
transform.Translate (Input.GetAxisRaw ("Horizontal") * moveSpeed * Time.deltaTime, 0, 0);
if (grounded)
{
if (Input.GetButtonDown ("Jump"))
{
rb.AddForce (Vector2.up * jumpSpeed);
grounded = false;
}
}
}
void OnCollisionEnter2D (Collision2D coll){
if (coll.transform.tag == "Ground")
{
grounded = true;
}
}
}
Inspector window of the Player GameObject
Inspector window of the Ground GameObject
Your problem is you haven't tag the Ground GameObject as so. So in the
OnCollisionEnter2D
the character detects the collision, but theif (coll.transform.tag == "Ground")
will never be true. So it means the character can't begrounded
Since to be grounded is the first condition to check if the player pressed the Jump key. It is impossible it will ever jump
To solve this issue: You need to tag the Ground GameObject as so. In case you are not sure how to do that, on the Tag menu, create (if it doesnt exist already) a new tag called Ground. Then assign in that same menu the Ground Tag to the Ground GameObject. Here you can learn how in case you need a visual reference:
https://docs.unity3d.com/Manual/Tags.html
Edit: You can try this script if everything fails. It should work. I used my self some time ago, I cleaned the code so to leave only what you need to move the character in the x and y axis. Hope to have included everything you need:
So things to take into account:
Instead of tag the ground, you create a layer with everything you consider ground. That will include possible platforms the character may jump over. Pass as a parameter this layer to the script in the inspector
You need to place an empty GameObject in the feet of the character. You will drag and drop that GameObject in the editor onto the groundCheck public variable.
Instead of OnTriggerEnter, you will use
Physics2D.Linecast
which will trave a line from the position of the character to under its feet (where you should have place the Transform mentioned in the previous step) and if in the middle there is an element of the groundLayer, it means the character will be grounded.Let me know if anything is not clear or if you find some bug.