2D jump height proportional to '' hold space'' and fixed distance

Hi everyone!

I have some problems with a code in C# for jumping in 2D. Basically I want my character to jump proportionally high to the amount of time the user holds the space key. Ofcourse there is also a maximum height of jump which can never be exceeded. Additionally, the character always jumps fixed amount of units to the left (without pressing any additional keys).

I already tried some codes from this forum which deal with similar problems but none of them seem to work or maybe I’m just not good enough at modifying them. Anyway, I thought it would be best to start from the beginning. Could you please give me some suggestions?

So far I have the following code for the vertical component of the jump:

void Jump ()
	{
		
		if (Input.GetKey (KeyCode.Space)) {
			rigidbody2D.AddForce(new Vector2(0, 1), ForceMode2D.Impulse);
		}
     }

Works fine, but I don’t know how to add the following funtionality:

  • Character jumps on release of the space button and not the same moment it’s pressed
  • It’s not possible to jump above certain (max) height
  • Fixed horizontal component of jump (left) without pressing additional keys

This should do what you want:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float _timeHeld = 0.0f;
    public float _timeForFullJump = 2.0f;
    public float _minJumpForce = 0.5f;
    public float _maxJumpForce = 2.0f;
    public float _leftJumpForce = 1.0f;

void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            _timeHeld = 0f;
        }
        if (Input.GetKey(KeyCode.Space))
        {
            _timeHeld += Time.deltaTime;
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Jump();
        }
}

    public void Jump()
    {
        float verticalJumpForce = ((_maxJumpForce - _minJumpForce) * (_timeHeld / _timeForFullJump)) + _minJumpForce;
        if (verticalJumpForce > _maxJumpForce)
        {
            verticalJumpForce = _maxJumpForce;
        }
        Vector2 resolvedJump = new Vector2(-_leftJumpForce, verticalJumpForce);
        rigidbody2D.AddForce(resolvedJump, ForceMode2D.Impulse);
        Debug.Log(resolvedJump.ToString());
    }
}

Where _timeForFullJump is the time that the spacebar must be held down in seconds to jump at _maxJumpForce. _minJumpForce, _maxJumpForce, and _leftJumpForce may have to be scaled up drastically depending on your scale, as I tested with fairly small sprites. Input.GetKeyDown() is called on the frame that a button is pressed, Input.GetKey() is called on all frames that the key is held down for, and Input.GetKeyUp() is called on the frame that the key is lifted on.

Hope this helps,
Bentley