- Home /
Fixing a jumping script in C#
enter code hereusing UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float maxSpeed = 15;
public float jumpForce = 800f;
void FixedUpdate () {
this.rigidbody2D.velocity = new Vector2 ( Input.GetAxis("Horizontal") * maxSpeed ,this.rigidbody2D.velocity.y);
if (Input.GetKeyDown (KeyCode.Space)) {
rigidbody2D.AddForce(new Vector2(0,jumpForce));
}
}
}
So this is my code for jumping with the sprite, but the problem is, once i hit space bar and i hit the space bar again, the sprite will just keeping jumping and jumping until i stop hitting the space bar.
Answer by Stygtand · Jun 08, 2014 at 09:03 AM
Then you press the jump button, you signal the event "input.getkeydown". This happens in a fixed update. If i recall right, that happens aprox every 0.33 seconds.
Depending on your game, the best way to do resolve this issue, is A. Put a jump count on. This can give your player the ability to double jump or even triple jump, if thats what you want.
B. If you just want your place to jump once. Implement a method to see if unity is grounded.
Heres an example you could use. You propperly need to redefine it.
bool jumping = false;
void Update()
{
if (input.GetKeyDown (KeyCode.Space) && !jumping) // if key down and is not already jumping
{
jumping = true;
}
}
void FixedUpdate ()
{
this.rigidbody2D.velocity = new Vector2 ( Input.GetAxis("Horizontal") * maxSpeed ,this.rigidbody2D.velocity.y);
if (jumping ) // if you are allowed to jump continue
{
rigidbody2D.AddForce(new Vector2(0,jumpForce));
jumping = false; // limits jumping
}
}
If i recall right, that happens aprox every 0.33 seconds.
You don't recall right. http://docs.unity3d.com/ScriptReference/Time-fixedDeltaTime.html