Hi, im starting to learn javascript and having problems with this small script. What im trying to do is when i press Fire2 i want my movement speed to increase. Can anyone help me find the problem within this script
#pragma strict
function Start(){}
function Fast ()
{
var speed = 0
if (Input.GetButtonDown ("Fire2"))
{
speed = 5;
}
}
function Update () {
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 1 + (speed);
var z = Input.GetAxis("Vertical") * Time.deltaTime * 1 + (speed);
transform.Translate(x, 0, z);
}
OK, but what's the error that it gives to you? By the way, I've tried to modify your script. This would be the logic:
#pragma strict
var speed = 1;
function Fast (){
if (Input.GetButton("Fire2"))
speed = 6;
else
speed = 1;
}
function Update () {
Fast();
var x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
var z = Input.GetAxis("Vertical") * Time.deltaTime * speed;
transform.Translate(x, 0, z);
}
EDIT: The errors that you've done:
You have declared Fast() function, but you have never called that. Now, The Update() function calls it every frame; before, it was never executed.
Declare speed at the top of the script. You are using pragma strict, and the Update() function, that uses that variable, had no visibility of it.
The speed formula was wrong to your purpose. You calculated Time.deltaTime * 1 + speed, but you want Time.deltaTime * (1 + speed). I've simplifed the calculation further, putting the speed assignment to value 6, directly.
Where are you calling the Fast(). You should call the Fast() in the Update(), so that it will run every frame. And make the speed variable, you have initialized in the Fast function a global variable.
var speed = 0;
function Fast()
{
if (Input.GetButtonDown ("Fire2"))
{
speed = 5;
}
}
function Update()
{
Fast();
var x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
var z = Input.GetAxis("Vertical") * Time.deltaTime * speed;
transform.Translate(x, 0, z);
}