- Home /
Character moves when holding shift
I am still trying to learn how to code in C# and I am trying to make a 2D platformer game and everything is working well except for my walk/sprint buttons. While holding 'A' or 'D' you walk in that direction of the key. If you hold shift while holding any of the two you will sprint in that direction but for some reason if you just hold the shift button it makes my character walk regardless if I hold 'A' or 'D'. I want the shift button to only work if I hold a walk button and I have tried if else statements but kept getting errors. Please help!
public float moveSpeed;
public float sprintSpeed;
public float jumpHeight;
private bool Grounded;
public Transform GroundCheck1;
public LayerMask groundLayer;
public float groundCheckRadius;
float someScale;
private Rigidbody2D rb;
private gameMaster gm;
void Start ()
{
someScale = transform.localScale.x;
rb = GetComponent<Rigidbody2D> ();
gm = GameObject.FindGameObjectWithTag ("GameMaster").GetComponent<gameMaster> ();
}
void FixedUpdate ()
{
Grounded = Physics2D.OverlapCircle (GroundCheck1.position, groundCheckRadius, groundLayer);
}
void Update ()
{
if (Input.GetKey (KeyCode.D))
{
transform.localScale = new Vector2 (someScale, transform.localScale.y);
transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
transform.localScale = new Vector2 (-someScale, transform.localScale.y);
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftShift))
{
transform.Translate (Vector3.right * sprintSpeed * Time.deltaTime);
}
if (Grounded == true)
{
if (Input.GetKeyDown (KeyCode.Space))
rb.AddForce (new Vector2 (0, 10), ForceMode2D.Impulse);
}
}
void OnTriggerEnter2D (Collider2D col)
{
if (col.gameObject.tag == "Coin")
{
Destroy (col.gameObject);
gm.points += 1;
}
}
}
Answer by Exceptione · May 11, 2017 at 03:53 PM
Vector3.right is always (1, 0, 0) or some variation of that, can't remember.
For your if statement when checking if shift is pressed, add a condition to check if the player is walking.
if (Input.GetKey(KeyCode.LeftShift) && (Input.GetKey(KeyCode.A) ||Input.GetKey(KeyCode.D)))
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
Checking for an object at a certain position 2 Answers
2D platformer levers and moving platforms question. 0 Answers