- Home /
Struggling with jumping!
I'm making a simple Unity 2D game. I am trying to make my character jump properly. At the moment when i press down spacebar repeatably the character will keep jumping till he hits the top of the screen. Here's the code:
#pragma strict
var moveLeft : KeyCode;
var moveRight : KeyCode;
var Jump : KeyCode;
var speed : float = 4;
var JumpHeight : float = 10;
function Update ()
{
if (Input.GetKey(moveLeft))
{
rigidbody2D.velocity.x = speed *-1;
}
else if (Input.GetKey(moveRight))
{
rigidbody2D.velocity.x = speed;
}
else
{
rigidbody2D.velocity.y = 0;
}
if (Input.GetKeyDown(Jump))
{
rigidbody2D.velocity.y = JumpHeight;
}
else if (Input.GetKeyDown(Jump))
{
rigidbody2D.velocity.y = 0;
}
}
Answer by Jeff-Kesselman · Jun 03, 2014 at 10:04 PM
These lines of code make no sense.
Lets see if you can figure out why...
if (Input.GetKeyDown(Jump))
{
rigidbody2D.velocity.y = JumpHeight;
}
else if (Input.GetKeyDown(Jump))
{
rigidbody2D.velocity.y = 0;
}
Answer by Kmanthe2 · Oct 17, 2014 at 06:42 PM
It sounds like you need to check if your character is grounded.
I have not played with 2d in unity yet, but in 3d the logic is something like this:
if (controller.isGrounded)
{
if (Input.GetButtonDown("Jump")))
{
velocity +=transform.up * jumpPower * Time.deltaTime ;
}
}
I hope at the very least that this can help you start searching in the right direction. Good luck with finding the answer.
Answer by DocMcShot · Oct 17, 2014 at 07:05 PM
I think you have 2 things going on here. I typically use C#, but I'll try some Javascript :)
Remove the:
else if (Input.GetKeyDown(Jump))
{
rigidbody2D.velocity.y = 0;
}
Next, you should add your force to your jump height by using the rigidbody2d.AddForce() function. You'll most likely have to bump your JumpHeight up quite a bit though. Like so:
if (Input.GetKeyDown(Jump))
{
rigidbody2D.AddForce(0, JumpHeight, 0);
}
Lastly, just some closing thoughts. You'll need to add a bool that checks if the Jump button was just pushed or you'll be able continuously jump. Also, If you use the AddForce() method, you should probably put that in the FixedUpdate() to make it more accurate. Hope this helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220613150716im_/https://answers.unity.com/themes/thub/images/avi.jpg)