I’m currently working on my first solo project, which is a fairly rudimentary flying game. I’ve got the basic physics working now, so I’ve decided to start implementing some other necessary functions. One of these is the throttle.
The throttle is intended to work like in Pilotwings 64, where if no button is pressed, the throttle is set to medium, then you can press the accelerator button to max the throttle out and the decelerator to nearly cut power to the engine completely.
The plane behaved fine when thrust was dictated by a static variable called “thrust”, but when I implemented this new feature, the plane doesen’t move at all.
Any ideas?
Ok some basics about variable scope. When you have an opening curly bracket you always start a new scope which ends at the corresponding closing bracket. Every variable declared within that brackets do no longer exist once you leave that scope.
Just in case a declaration of a variable is where it is defined. You declare a variable by specifing a type followed by a name.
So in each of your code blocks you declare a local variable which only exists *within those brackets.
What you should do, since you want to set the throttle in a one-time event, declare the variable at class scope (i.e. outside of the method you have that code in).
public class SomeClass : MonoBehaviour
{
float throttle; // declare it here.
void Update()
{
if (Input.GetKeyDown("a"))
{
throttle = HighThrottle;
}
if (Input.GetKeyDown("z"))
{
throttle = LowThrottle;
}
else
{
throttle = MediumThrottle;
}
float AirDensity = 2000 - (transform.position.y / 3);
rb.AddRelativeForce(Vector3.forward * throttle * AirDensity);
}
}