• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by mnov · Jan 12, 2015 at 10:12 PM · 2djump

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

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Kevin9595 · May 07, 2015 at 07:33 AM 0
Share

Hi! I know this might have been a long time ago, and I apologize for my lack of knowledge in C#, but I tried out what you guys said, but I can't seem to get it right. I get no errors, but my character (a cube) doesn't seem to move. Do you guys $$anonymous$$d looking at my script to see what's wrong with it?

using UnityEngine; using System.Collections;

public class PlayerController : $$anonymous$$onoBehaviour { public float _timeHeld = 0.0f; public float timeForFullJump = 2.0f; public float $$anonymous$$JumpForce = 0.5f; public float _maxJumpForce = 2.0f; public float _leftJumpForce = 1.0f; public float _leftJumpForceTotal = 2.0f;

 void Update ()
 {
     if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
     {
         _timeHeld = 0f;
     }
     if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Space))
     {
         _timeHeld += Time.deltaTime;
     }
     if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.Space))
     {
         Jump();
     }
 }
 
 public void Jump()
 {
     float verticalJumpForce = ((_maxJumpForce - _$$anonymous$$JumpForce) * (_timeHeld / _timeForFullJump)) + _$$anonymous$$JumpForce;
     if (verticalJumpForce > _maxJumpForce) {
         float initialVelocity = (verticalJumpForce / GetComponent<Rigidbody2D> ().mass);
         float timeInAir = ((2 * initialVelocity) / GetComponent<Rigidbody2D> ().gravityScale);
         float leftJumpForceResolved = _leftJumpForceTotal / timeInAir;
     

         verticalJumpForce = _maxJumpForce;
     
         Vector2 resolvedJump = new Vector2 (-leftJumpForceResolved, verticalJumpForce);
         GetComponent<Rigidbody2D> ().AddForce (resolvedJump, Force$$anonymous$$ode2D.Impulse);
         Debug.Log (resolvedJump.ToString ());
     }
 }

}

Thank you so much!!!

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Bentley · Jan 13, 2015 at 01:14 AM

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

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mnov · Jan 13, 2015 at 07:30 PM 0
Share

Oh my god, this is amazing!! You have no idea how much time you just saved me. Let me illustrate how grateful I am - if a genie gave me three wishes yesterday, my wish would be to have this code. If a genie gave me three wishes today, my wish would be that all your wishes come true! Seriously, thanks a lot.

The only thing I'm still struggling with is fixed jump to the left. For example, if I hold the button for 1 second, the player jumps 1 unit to the left, but if I hold it for 3 seconds, the player jumps 5 units to the left. I'm trying to make it jump 5 units to the left, regardless of how long I hold the space button... I tried to modify the vertical jump part of code and use it also for the horizontal jump code by settting $$anonymous$$JumpLeft / $$anonymous$$JumpRight to the same value (11) or at least almost the same (11 and 11.1). Unfortunately the jump distance to the left still depends on the amount of time I hold the space button. Could you please help me with this as well?

avatar image mnov · Jan 17, 2015 at 06:49 PM 0
Share

Ok, so this is the best solution I could come up with. I added the following line to the Jump() function:

 float _leftJumpForce = (1700f / verticalJumpForce);

The higher the jump, the lower _leftJumpForce is applied, so the jump distance to the left is approximately the same at both high and low jumps. I know the solution is rather simple so if you could give me your input on this I would really appreciate it. Cheers!

avatar image Bentley · Jan 18, 2015 at 08:24 PM 0
Share

Alright, sorry I didn't even think about the constant left jump when I first answered the question but I've got a solution for that too. Add these three lines after the if statement in Jump()

         float initialVelocity = (verticalJumpForce / rigidbody2D.mass);
         float timeInAir = ((2 * initialVelocity) / rigidbody2D.gravityScale);
         float leftJumpForceResolved = _leftJumpForceTotal / timeInAir;

And then change the "-_leftJumpForce" in line 35 to "-leftJumpForceResolved"

avatar image mnov · Jan 21, 2015 at 05:11 PM 0
Share

I'm guessing the _leftJumpForceTotal is a public float variable, defined according to the desired jump distance to the left? Thanks a lot for your help, I really appreciate it!

avatar image nicolosky · May 14, 2015 at 09:44 PM 0
Share

I get this error while using the same script as yours.. any help pls? Assets/scripts/Player.cs(88,29): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody2D.AddForce(UnityEngine.Vector2, UnityEngine.Force$$anonymous$$ode2D)'

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Why does my 2d player stick to the floor when he lands? 0 Answers

Unity 2D Top Down Jump 1 Answer

Problem with joints 2 Answers

Drag and jump mechanics? 2 Answers

My player wont jump (2d game) 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges