Im new to coding and i have this problem...
My Goal is: If you press 'A' the variable subtracts 1.
If you press 'D' the variable adds 1.
So that you can only toggle through, "-1, 0 and 1"
The problem is that if I put the code inside "function Update", it will skip '0' too quickly :( .
Heres the JavaScript…
var mover : int = 0;
function Start ()
{
if (Input.GetButton(“Left”))
{
mover = mover -1;
}
if (Input.GetButton("Right"))
{
mover = mover + 1;
}
}
function Update ()
{
//this is so that it doesnt go higher than 1.
if (mover > 1)
{
mover = 1;
}
//this is so that it doesnt go lower than -1.
if (mover < -1)
{
mover = -1;
}
No, KuriKrunch, don't use Start(). That function is executed only once when the game starts, and that's useless to your purpose (the keys' pressure is never checked). Try this:
var mover = 0;
function Update(){
//Here, we check for keys pressure
if (Input.GetButton("Left"))
mover -= 1;
else if (Input.GetButton("Right"))
mover += 1;
//Here, we check that mover is inside {-1, 0, 1}
if (mover > 1)
mover = 1;
else if (mover < -1)
mover = -1;
}
I guess the best way to do what you need is using Input.GetButtonDown().
This way you only get a true value the first frame you press the button.
var mover = 0;
function Update(){
//Here, we check for keys pressure
if (Input.GetButtonDown("Left"))
mover -= 1;
else if (Input.GetButtonDown("Right"))
mover += 1;
//Here, we check that mover is inside {-1, 0, 1}
if (mover > 1)
mover = 1;
else if (mover < -1)
mover = -1;
}
Ooohh… I almost forgot…
This way I told you, each time you press the button it’ll add (or subtract) just one time.
So, if your “mover” variable is “-1” and you press “D”, to variable will add “1” and become “0”, for as long as you keep the button pressed.
If you want to add it again, you’ll have to press “D” again.