- Home /
Button Press and Hold Animations
Hello I was wondering if anybody could explain to me why this code only works some of the time not all of the time, it's supposed to allow the user to hold down the space bar to slide after a given amount of time, but then jump when it's pressed, however sometimes holding it makes it jump and only occasionally makes it slide.
public class JumpScript : MonoBehaviour {
Animator anim;
public AudioClip JumpSound;
public float jumpSpeed = 1000f;
float jumpRate = 1.2f;
bool canJump = true;
private float slideTime = 10.0f;
public float jumpTime = 5.0f;
void Start()
{
this.gameObject.AddComponent<AudioSource>();
this.GetComponent<AudioSource>().clip = JumpSound;
anim = GetComponent<Animator>();
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) TryJump();
if (Input.GetKey(KeyCode.Space) && Time.time > slideTime) Slide();
}
IEnumerator JumpCooldown() {
canJump = false;
yield return new WaitForSeconds(jumpRate);
canJump = true;
yield break;
}
void TryJump() {
if (!canJump) return;
Jump();
StartCoroutine(JumpCooldown());
}
void Jump() {
if(Input.GetButtonDown("Jump") && Time.time < slideTime)
{
audio.PlayOneShot(JumpSound);
rigidbody2D.AddForce(new Vector2(0, jumpSpeed));
anim.Play("Jumping");
}
}
void Slide()
{
if(Input.GetButtonDown("Jump") && Time.time > slideTime)
{
slideTime = Time.time + jumpTime;
anim.Play("Sliding");
}
}
}
Help me please!
Answer by MolochSim · Nov 10, 2014 at 12:50 PM
I can see several problems in your code. First, you are reading the input multiple times. Only use if (GetButtonDown and GetButton) once - in Update(). Remove it from Slide() and Jump(). It only registers once when the button is pressed. Also, Time.time is the overall time since the game has launched in seconds. You need some sort of counter for the time the button has been pressed. Use a float variable for that.
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) TryJump();
if (Input.GetKey(KeyCode.Space) timeHeld += Time.deltaTime;
if (timeHeld >= slideTime) Slide();
if (InputGetKeyUp(KeyCode.Space)) timeHeld = 0f;
}
Decide on using either GetKey or GetButton to avoid future confusion.
I've tried messing around with your method and I always feel I'm the tiniest bit closer to solving it, but my problem still arises where if the button is held he will still perform the jump action because the button has been pressed, is there a way to allow it to read how long the button has been held for first and then decide what to do? I feel like the answers staring in me in the face and I can't find it!