- Home /
Hold Spacebar, Stop Jumping
Hello,
My character jumps using spacebar. When I HOLD spacebar down, he jumps over and over and over. I want him to perform the jump each time spacebar is pressed; but not when spacebar is held down. The script I'm using is below:
using UnityEngine;
using System.Collections;
public class Walker : MonoBehaviour {
private IRagePixel ragePixel;
public enum WalkingState {Standing=0, WalkRight, WalkLeft, JumpUp};
public WalkingState state = WalkingState.Standing;
public RagePixelSprite space;
public float walkingSpeed = 10f;
void Start () {
ragePixel = GetComponent<RagePixelSprite>();
}
void Update () {
if (Input.GetKey("space"))
{
state = WalkingState.JumpUp;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
state = WalkingState.WalkLeft;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
state = WalkingState.WalkRight;
}
else
{
state = WalkingState.Standing;
}
switch (state)
{
case (WalkingState.JumpUp):
ragePixel.SetHorizontalFlip(false);
ragePixel.PlayNamedAnimation("JUMP", false);
break;
case(WalkingState.Standing):
ragePixel.SetHorizontalFlip(false);
ragePixel.PlayNamedAnimation("STAY", false);
break;
case (WalkingState.WalkLeft):
ragePixel.SetHorizontalFlip(false);
ragePixel.PlayNamedAnimation("WALK", false);
break;
case (WalkingState.WalkRight):
ragePixel.SetHorizontalFlip(false);
ragePixel.PlayNamedAnimation("WALK", false);
break;
}
}
}
Any help is greatly appreciated. Thank you so much!
Answer by Drakestar · Jun 21, 2012 at 07:43 PM
You can use the Input.GetKeyDown and Input.GetKeyUp. Set a bool to true when it's down, and when GetKeyUp is captured and the bool is true, jump (and set the bool back to false).
Thank you for the help. I'm having problems adding a bool because it never recognizes the variable I set. I tried using public, private, etc but none of them worked. do I need to label it differently?
A private field (= a variable that belongs to the class, declared outside any methods) should always retain its state between function calls.