Hi! I’m having an issue I’ve been dealing with for a while now and decided to ask on here. In my 2D platformer test game on start my player can only jump once and when it reaches the ground it gets stuck in the jumping/in-air animation. It is acting like it isn’t detecting the ground. I am using a collider that is set to trigger on enter and set the grounded variable to true. I also set it up for double jumping, but that doesn’t work either. I’d appreciate any help I can get with this, thank you.
Here is my code for the character:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float maxSpeed = 3;
public float speed = 20f;
public float jumpPower = 500f;
public bool grounded;
public bool doubJump;
private Animator anim;
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if(Input.GetAxis("Horizontal") < -.01f)
{
transform.localScale = new Vector3(-5,5,1);
}
if (Input.GetAxis("Horizontal") > .01f)
{
transform.localScale = new Vector3(5, 5, 1);
}
if (Input.GetButtonDown("Jump"))
{
gameObject.GetComponent<GroundCheck>();
if (grounded == true)
{
rb2d.AddForce(Vector2.up * jumpPower);
grounded = false;
doubJump = true;
}
if (grounded == false && doubJump)
{
rb2d.AddForce(Vector2.up * jumpPower);
doubJump = false;
}
}
}
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
rb2d.AddForce((Vector2.right * speed) * h);
if (rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
}
And here is the ground check code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundCheck : MonoBehaviour {
public Player player;
void Start()
{
player = gameObject.GetComponentInParent<Player>();
}
void onTriggerEnter2D(Collider2D col)
{
player.grounded = true;
}
void onTriggerStay2D(Collider2D col)
{
player.grounded = true;
}
void onTriggerExit2D(Collider2D col)
{
player.grounded = false;
}
}