Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hi ! jumping and crouch aren't working. #1

Open
joshaabraham opened this issue Oct 30, 2018 · 15 comments
Open

Hi ! jumping and crouch aren't working. #1

joshaabraham opened this issue Oct 30, 2018 · 15 comments

Comments

@joshaabraham
Copy link

Hi, first thank for your tutorials. its very good.
bout the character 2d movement, here is a problem I meet, I effectivly press up and down arrows or 'w' and 's' ... or space (I've set everything right about the input), but the caracter dosen t jump or crouch. I put a Debug Log inside the if(Input.Get ... ) and it seems that my key are pressed. So I wonder what's going on.

see below

if (Input.GetButtonDown("Jump"))
{
Debug.Log("Jumped");
jump = true;
}
if (Input.GetButtonDown("Crouch"))
{
Debug.Log("Crouched");
crouch = true;
}
else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}

have you got any idea ?

@PlzDntBlm
Copy link

Check if you've already assigned the gameObjects "GroundCheck" and "CeilingCheck" to the controller script.

@joshaabraham
Copy link
Author

hi ! thank for your reply :) I 've let this pb aside for a couple of days. but yes, my ceiling and groundCheck are positionned correctly. I continue to investigate . Once again, thank you for your help PlzDntBlm.

@LliamMRankins
Copy link

LliamMRankins commented Dec 12, 2018

hey, I'm having a similar problem to this. I've triple checked my Ceiling/ground Checks. used Debug.Log to make sure that my "Input.GetKeyDown("f")" is working (It does) and I have no clue what's wrong

code:

bool Crouching = false;

void Update ( ) {
if (Input.GetKeyDown("f"))
{
Crouching = true;
} else if (Input.GetKeyUp("f"))
{
Crouching = false;
}
}

void FixedUpdate()
{
    Contoler.Move(HorizontalMove * Time.fixedDeltaTime * MoveSpeed * 80, Crouching, Jump);
    Jump = false;
}

also, on another note. my box collider (the one that is to be disabled) is constantly flickering, on and off.

@TheDrLamb
Copy link

I found a solution, if you change the FixedUpdate section of the CharacterController2D script to a LateUpdate it eliminates the issue with jumping.

@eliasg13
Copy link

eliasg13 commented Apr 1, 2019

Hi! Had a problem too when setting the checks for ceiling and ground. The editor always returned me that they where not declared, and they'll always return null. Just removed the "serializeField" and turn the variable to public. That solved my problem. Here you have my edited script.

`
using UnityEngine;
using UnityEngine.Events;

public class CharacterController2D : MonoBehaviour
{
    [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    public LayerMask whatIsGround;                          // A mask determining what is ground to the character
    public Transform groundCheck;                           // A position marking where to check if the player is grounded.
    public Transform ceilingCheck;                          // A position marking where to check for ceilings
    public Collider2D crouchDisableCollider;                // A collider that will be disabled when crouching

    const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    private bool m_Grounded;            // Whether or not the player is grounded.
    const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    private Rigidbody2D m_Rigidbody2D;
    private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    private Vector3 m_Velocity = Vector3.zero;

    [Header("Events")]
    [Space]

    public UnityEvent OnLandEvent;

    [System.Serializable]
    public class BoolEvent : UnityEvent<bool> { }

    public BoolEvent OnCrouchEvent;
    private bool m_wasCrouching = false;

    private void Awake()
    {
        m_Rigidbody2D = GetComponent<Rigidbody2D>();

        if (OnLandEvent == null)
            OnLandEvent = new UnityEvent();

        if (OnCrouchEvent == null)
            OnCrouchEvent = new BoolEvent();
    }
 
    private void FixedUpdate()
    {
        bool wasGrounded = m_Grounded;
        m_Grounded = false;

        // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
        // This can be done using layers instead but Sample Assets will not overwrite your project settings.
        Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, k_GroundedRadius, whatIsGround);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
            {
                m_Grounded = true;
                if (!wasGrounded)
                    OnLandEvent.Invoke();
            }
        }
    }


    public void Move(float move, bool crouch, bool jump)
    {
        // If crouching, check to see if the character can stand up
        if (!crouch)
        {
            // If the character has a ceiling preventing them from standing up, keep them crouching
            if (Physics2D.OverlapCircle(ceilingCheck.position, k_CeilingRadius, whatIsGround))
            {
                crouch = true;
            }
        }

        //only control the player if grounded or airControl is turned on
        if (m_Grounded || m_AirControl)
        {

            // If crouching
            if (crouch)
            {
                if (!m_wasCrouching)
                {
                    m_wasCrouching = true;
                    OnCrouchEvent.Invoke(true);
                }

                // Reduce the speed by the crouchSpeed multiplier
                move *= m_CrouchSpeed;

                // Disable one of the colliders when crouching
                if (crouchDisableCollider != null)
                    crouchDisableCollider.enabled = false;
            }
            else
            {
                // Enable the collider when not crouching
                if (crouchDisableCollider != null)
                    crouchDisableCollider.enabled = true;

                if (m_wasCrouching)
                {
                    m_wasCrouching = false;
                    OnCrouchEvent.Invoke(false);
                }
            }

            // Move the character by finding the target velocity
            Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
            // And then smoothing it out and applying it to the character
            m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);

            // If the input is moving the player right and the player is facing left...
            if (move > 0 && !m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
            // Otherwise if the input is moving the player left and the player is facing right...
            else if (move < 0 && m_FacingRight)
            {
                // ... flip the player.
                Flip();
            }
        }
        // If the player should jump...
        if (m_Grounded && jump)
        {
            // Add a vertical force to the player.
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }
    }


    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        m_FacingRight = !m_FacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}`

@Kiwi06
Copy link

Kiwi06 commented May 1, 2019

To fix the jump make the ground check and the ceiling check a child of the player, this worked for me

@PuppyShogun
Copy link

I've spent hours and hours trying to get this to work as a straight up beginner. I've copied the code exactly. 2019.1.5f1 version. I was able to troubleshoot that somewhere the code is causing Crouch to be always on. Changing from Serialize to Public as suggested above simply flips my problem and I'm able to crouch and uncrouch but not jump.

Also, most likely the source of all of the issues is somewhere in the code for detecting if a player is crouching under a ceiling. It is ineffective. When I can get crouching working, the code is completely ignored and the player character just stands up into the overhead block and cannot move. This is literally the worst introduction to Unity. Is it always like this? This is barely any code at all and apparently different update versions provide different results.

@paprikka
Copy link

Fixed it temporarily with LateUpdate, but this seems a bit hacky.

The IsJumping param gets changed back to false as soon as the jump physics kick in.
I suspect that this is due to the fact that withing the first few frames the GroundCheck transform is still within the radius specified by k_GroundedRadius. I imagine that the race condition could be fixed with a bit of state in the CharacterController2D class or even better, determining if the player character just started the jump based on the velocity vector?

Putting this here because it'll take me a while to code a proper solution but you might be able to apply fixes to your code sooner (I'm a software engineer but I'm not well versed in Unity).

@paprikka
Copy link

Ha, someone already submitter a PR, sweet! #3

@joshhales1
Copy link

also, on another note. my box collider (the one that is to be disabled) is constantly flickering, on and off.

I know this is a bit late but to fix this make sure you're not setting ground to be on the same layer as anything like the camera. Changed this and it fixed it.

@sawyermcb
Copy link

I moved my ceiling check up a little more and it then worked. Im using a tilepalette environment with the auto box colliders on painted elements. Good luck!

@Kahilio
Copy link

Kahilio commented Jul 12, 2020

Es klappt nicht zu Springen

Hier mein code:

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

public class PlayerMovement : MonoBehaviour{

public CharacterController2D controller;

public float runSpeed = 40f;

float horizontalMove = 0f;
bool jump = false;
bool crouch = false;

void Update(){
    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

    if (Input.GetButtonDown("jump"))
    {
      jump = true;
    }

    if (Input.GetButtonDown("crouch"))
    {
      crouch = true;
    }else if (Input.GetButtonUp("crouch"))
    {
      crouch = false;
    }
}

void LateUpdate(){
    controller.Move(horizontalMove * Time.deltaTime, crouch, jump);
    jump = false;
}

}

@ChristTheMaster
Copy link

how to fix it when u press the play button it deletes your box collider without pressing the crouch button? Plzzz help.

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

public class PlayerMovement : MonoBehaviour
{

public CharacterController2D controller;
public float runSpeed = 40f;

bool jump = false;
bool crouch = false;

float horizontalMove = 0f;


 void Update()
{
    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

    if (Input.GetButtonDown("Jump"))
    {
        jump = true;
    }

    if (Input.GetButtonDown("Crouch"))
    {
        crouch = true;
    }
    else if (Input.GetButtonUp("Crouch"))
    {
        crouch = false;
    }
}

private void LateUpdate()
{
    controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
    jump = false;
}

}

@LQPewds
Copy link

LQPewds commented Dec 26, 2020

I tried all of the recommendations on this post but still I cant get it to jump.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

public CharacterController2D controller;

public float runSpeed = 40f;

float horizontalMove = 0f;

bool jump = false;



void Update()
{
    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

    if (Input.GetButtonDown("Jump"))
    {
        jump = true;
    }
}

void FixedUpdate()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
}
}

And for the ceiling/ground check I have no idea where to place them

@DanteInfernal7
Copy link

This is very late but after some time of fidgeting with it I figured out that you gotta keep the ground object in a different layer than the player which was what I was doing and that ground check and ceiling check in the same layer as ground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests