- Home /
Simple 2-Button-Mash script
Hello everyone, since im fairly new to unity, i am having big problems comming up with a solution for my problem. It's a simple 100-m-dash game. So by repeatedly pressing 2 buttons ("left" and "right") you gain momentum. The faster you mash the correct buttons, the faster you get. But pressing the wrong button slows you down... Pressing nothing does nothing.
Here's the Code:
public class PlayerMovement : MonoBehaviour {
Rigidbody PlayerRigidbody;
int succRep = 0;
float reqInput = -1f;
Vector3 movement;
void Awake(){
PlayerRigidbody = GetComponent<Rigidbody> ();
Debug.Log (reqInput);
}
void FixedUpdate()
{
Dash ();
}
void Dash()
{
float v = Input.GetAxisRaw ("Horizontal");
//Debug.Log (v);
if (v == reqInput && Input.GetButtonDown("Horizontal"))
{
//Debug.Log (v);
//Debug.Log ("SuccRep="+succRep);
succRep++;
PlayerRigidbody.AddForce(new Vector3(1f,0f,0f)*succRep);
reqInput = reqInput * -1;
} else {
if(v == 0)
{
}
else {
if (v == (reqInput*-1) && Input.GetButtonDown("Horizontal"))
{
PlayerRigidbody.AddForce(new Vector3(-1f*succRep/2,0f,0f));
succRep = 0;
}
}
}
}
}
So the problem i am having is: that the required Input ("reqInput") isn't alternating correctly. And i think it is because the game isn't properly checking the input given.
A big thank you in advance!
Answer by Mmmpies · Jan 21, 2015 at 03:35 PM
So GetAxisRaw it either -1, 0 or 1 as I understand it
// At the top
private bool reqInput = false;
void Dash()
{
int v = Input.GetAxisRaw("Horizontal");
if((v == -1 && !reqInput) || (v = 1 && reqInput)
{
succRep++;
reqInput = !reqInput
PlayerRigidbody.AddForce(new Vector3(1f,0f,0f)*succRep);
}
else if((v == -1 && reqInput) || ( v = 1 && !reqInput))
{
PlayerRigidbody.AddForce(new Vector3(-1f*succRep/2,0f,0f));
succRep = 0;
}
}
I've not tested the code though, and you might want to record the first movement and set the bool accordingly.
I think it'll still have issues as a frame is normally very fast so it's likely you'll still be pressing the same direction on the next frame. You could maybe set a float = Time.time + 0.3f and only call Dash is Time.time is greater than that value.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How To Accelerate/Decelerate Gradually With Torque GetAxis 1 Answer
Roll a ball camera problem? 1 Answer