- Home /
My character won't stop jumping!!!
vector2 JUMP; public float JumpHeight;
void Update () {
jumping();
}
public void jumping(){
if (Input.GetButtonDown ("Jump") && GetComponent<Rigidbody2D>().velocity.y==0 ) {
JUMP=new Vector2 (GetComponent<Rigidbody2D>().velocity.x,JumpHeight);
}
}
void FixedUpdate(){
GetComponent<Rigidbody2D> ().velocity = JUMP;
}
Can anyone tell me how can I fix it? I want to jump only once before I hit the ground, but when I push button jump it goes to air and won't stop jumping.
,
does your character just bonce a lot, or does it go up and not come back down?
okay, here is what's going on.
if you press the space bar, while the rigidbody's velocity is 0, it adds to the JumpHeight value to the Y axis causing it to go up, and not come back down.
if you did something like:
if( GetComponent().velocity.y>JumpHeight){ velocity.y==0; }
i don't work with 2Drigidbodies, but this may help,
if it ends up going through the floor.... well what went up, came back down.... at least...
Answer by SeaLeviathan · Jul 24, 2017 at 01:35 PM
The problem is that the first time you tell it to jump, you just set the velocity to something.
What you are probably looking for is the AddForce function.
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
Try looking at the example to get a better idea of how this component works!
{
public int JumpHeight;
public Rigidbody2D rb;
void Update()
{
jumping();
}
private void Start()
{
rb = GetComponent<Rigidbody2D>(); // or you can just manually set this in the inspector, as it is a public variable.
}
public void jumping()
{
if (Input.GetButtonDown("Jump"))
{
rb.AddForce((Vector2.up * JumpHeight));
}
}
void FixedUpdate()
{
jumping();
}
}
This will make it so that every time you press spacebar it jumps - what you were trying to do with the velocity.y = 0 would let you be able to spam the spacebar and jump endlessly, every time the jump apexes. Try instead a character controller, it has a built in grounded function. If you want to go full custom, however, you can use either raycasting or triggers or collision detections. The choice is really yours, if you want more help on any aspect of your character jumping just tell me!