- Home /
function Start () problem!!
hi :)
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;
}
}
Answer by Felipetnh · Jan 23, 2012 at 02:34 PM
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; }
..I don't know the rules very well, but I'm pretty sure marking an answer before you try is not the best way of doing this.
Answer by BiG · Jan 23, 2012 at 01:48 PM
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 tried your way... it works but it skips 0 if you hold the button a little too long. all it needed was "if (Input.GetButtonDown("Left"))" just like Felipetnh said...but still thanks for the help!
Answer by Felipetnh · Jan 23, 2012 at 02:52 PM
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.
Hope I could help.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
delete a cube with particles 0 Answers
change to glow texture on mouse click 0 Answers
On var enter 1 Answer
What am I doing wrong in this 1 Answer