- Home /
Making a flight script dependent on several variables activated by another script.
For a magic based game I am making, I need there to be a flight script which lets the player fly by pressing the space bar, but only after pressing the keys O P I. I tried doing it several ways. At this point my code looks like this:
function FixedUpdate ()
{
Debug.Log ("Update Called");
if (MainScript.flying == true)
{
if (Input.GetKey(KeyCode.Space))
{
Debug.Log ("Flight Attempted");
var input = new Vector3 (Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
GetComponent.<Rigidbody>().AddForce(input);
Debug.Log ("Flight Successful");
}
}
}
This does nothing, although all Debug.Logs are being triggered. I do not know if there is any way for this code to work, so it may be necessary to start from scratch. I really don't care anymore so long as it works. Keep in mind that I am relatively new to programming, so try to be specific in your answers as there are a lot of features that I have no clue how to use.
Answer by spencer_white · Jun 02, 2016 at 04:59 PM
First, make sure the object has a rigidbody. It's pretty obvious, but sometimes, people forget it.
Try saving rigidbody to a variable, so, at the beginning of the program, write,
public Rigidbody rb;
//You are using JS, so you may need to save it as a var instead of Rigidbody.
//Sorry, I don't get how JS variables work
Then, In void Start, write
function Start() {
rb = GetComponent<Rigidbody>();
}
Then, drag your object into where it says Rb in the editor, like so:
Hope it helped! And, Good luck on your game. Sounds like a great idea.
P.S: I don't know that my code will work. I used C# :/
var rb : Rigidbody;
function Start(){
rb = GetComponent.<Rigidbody>();
}
it's not mandatory but it will speed the game up a tad bit.