Walljump Problem - 2D Platformer

Hello, I’m quite new to Unity and game development and I’m making a little platformer prototype to get started and learn. I have a problem however, and that is that when I walljump and let go of the directional button (A/D) my walljump continues in the Y-axis but not in the X-axis.

I think I know what is causing the problem but I don’t know how to fix it. Please help!

The causation of the problem seems to be that my ‘horizontal’ (horizontal input) becomes 0 if you let go of the directional input, therefore if you multiply the xWallForce by ‘-horizontal’ which is zero, nothing happens on the X-axis. Here’s what i mean using a bit of my ‘wallJumping’ code:

if (wallJumping == true)
{
rb.velocity = new Vector2(xWallForce * -horizontal, yWallForce);
}

How can I make it so that the X-axis movement from the walljump continues until ‘wallJumpTime’ is over, independent from whether I let go of my directional input or not.

Full code:

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

public class PlayerMovement : MonoBehaviour
{
    public ParticleSystem dust;
    public ParticleSystem dashExplo;

    public float horizontal;
    public float speed = 8f;
    public float jumpingPower = 16f;
    public float fallGravityMultiplier = 1.5f;
    public bool isFacingRight = true;
    public bool airborn;

    private bool canDash = true;
    private bool isDashing;
    public float dashingPower = 40f;
    public float dashingTime = 0.2f;
    public float dashingCoooldown = 1f;

    bool isTouchingFront;
    public Transform frontCheck;
    bool wallSliding;
    public float wallSlidingSpeed;

    public bool wallJumping;
    public float xWallForce;
    public float yWallForce;
    public float wallJumpTime;
    public float jumpTime;

    private float jumpBufferTime = 0.2f;
    private float jumpBufferCounter;

    public float coyoteTime = 0.2f;
    private float coyoteTimeCounter;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private TrailRenderer tr;
    public float gravityScale;

    public void SetGravityScale(float scale)
    {
        rb.gravityScale = scale;
    }

    private void Start()
    {
        SetGravityScale(gravityScale);
        isFacingRight = true;
    }

    private void Update()
    {
        if (isDashing)
        {
            return;
        }

        horizontal = Input.GetAxisRaw("Horizontal");

        if (isGrounded() == true)
        {
            coyoteTimeCounter = coyoteTime;
        }
        else
        {
            coyoteTimeCounter -= Time.deltaTime;
        }

        if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Space))
        {
            jumpBufferCounter = jumpBufferTime;
        }
        else
        {
            jumpBufferCounter -= Time.deltaTime;
        }

        if (jumpBufferCounter > 0f && coyoteTimeCounter > 0f || jumpBufferCounter > 0f && coyoteTimeCounter > 0f)
        {
            createDust();
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);

            jumpBufferCounter = 0f;
        }

        if (Input.GetKeyUp(KeyCode.W) && rb.velocity.y > 0f || (Input.GetKeyUp(KeyCode.Space) && rb.velocity.y > 0f))
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);

            coyoteTimeCounter = 0f;
        }

        if (Input.GetKeyDown(KeyCode.LeftShift) && canDash)
        {
            StartCoroutine(Dash());
        }

        Flip();

        if (Input.GetKeyDown(KeyCode.Space) & wallSliding == true || Input.GetKeyDown(KeyCode.W) & wallSliding == true)
        {
            createDust();
            wallJumping = true;
            Invoke("SetWallJumpingToFalse", wallJumpTime);
        }
    }
    void SetWallJumpingToFalse()
    {
        wallJumping = false;
    }
    private void FixedUpdate()
    {
        if (isDashing)
        {
            return;
        }

        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);

        isTouchingFront = Physics2D.OverlapCircle(frontCheck.position, 0.5f, groundLayer);

        if (isTouchingFront == true && isGrounded() == false && horizontal != 0)
        {
            wallSliding = true;
        }
        else
        {
            wallSliding = false;
        }

        if (wallSliding == true)
        {
            rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
        }

        if (wallJumping == true)
        {
            rb.velocity = new Vector2(xWallForce * -horizontal, yWallForce);
        }
       
        if (rb.velocity.y < 0)
        {
            rb.gravityScale = gravityScale * fallGravityMultiplier;
        }
        else
        {
            rb.gravityScale = gravityScale;
        }

        if (isGrounded() == true)
        {
            airborn = false;
        }
        else if (isGrounded() == false)
        {
            airborn = true;
        }
    }

    public bool isGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.5f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            if (!isGrounded())
            {
                dust.Stop();
            }
            else if (isGrounded())
            {
                createDust();
            }
            Vector3 localScale = transform.localScale;
            isFacingRight = !isFacingRight;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }

    private IEnumerator Dash()
    {
        canDash = false;
        isDashing = true;
        float originalGravity = rb.gravityScale;
        rb.gravityScale = 0f;
        rb.velocity = new Vector2(transform.localScale.x * dashingPower, 0f);
        tr.emitting = true;
        createDashExplo();
        yield return new WaitForSeconds(dashingTime);
        tr.emitting = false;
        rb.gravityScale = originalGravity;
        isDashing = false;
        yield return new WaitForSeconds(dashingCoooldown);
        canDash = true;
    }

    void createDust()
    {
        dust.Play();
    }

    void createDashExplo()
    {
        dashExplo.Play();
    }
}

Thanks a lot!

Usually things like walljump are handled by setting some kind of flag or indicator that says “you are no longer walking, you are now walljumping.”

Same applies to other things like jumping or dashing or rolling or whatever.

That way you have specific code to sense when the end of that mode, such as a timer expiring, or reaching the end of the wall, or touching down, or whatever, and using that flag, decide how to handle inputs.

When working with these systems it can helpful to make a very specific level with features to help you test it quickly, such as a wall pressed right by the spawnpoint.

Then as you work, use logging to find out what is happening in realtime.

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.