2D spaceship controls, ship flies without key input :I
Hi, beeing a noob, I wonder why my 3d model spaceship already flies to the right without a button beeing pressed :D Also, how can I make it so that it only flies when I press a button, and stops when I release it ? Up/down works, left/right not, although its the same command...Thanks !
Public class Player_Control : MonoBehaviour {
void Start()
{
}
public float moveSpeed = 10f;
public float turnSpeed = 5f;
public float tiltAngle = 60f;
void Update()
{
if (Input.GetKey(KeyCode.DownArrow))
transform.Translate(Vector3.down * moveSpeed * Time.deltaTime);
if (Input.GetKey(KeyCode.UpArrow))
transform.Translate(Vector3.up * moveSpeed * Time.deltaTime);
Quaternion target2 = Quaternion.Euler(0, 0, 0);
if (Input.GetKey(KeyCode.RightArrow))
transform.rotation = target2;
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
Quaternion target = Quaternion.Euler(0, 180, 0);
if (Input.GetKey(KeyCode.LeftArrow))
transform.rotation = target;
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
Answer by Alex_May · Mar 25, 2019 at 09:59 PM
You need to put some of your code in a scope, or the compiler won't know which instructions to execute after your ifs. Use the curly braces for this. Here's your code with braces added that should work:
if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(Vector3.down * moveSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector3.up * moveSpeed * Time.deltaTime);
}
Quaternion target2 = Quaternion.Euler(0, 0, 0);
if (Input.GetKey(KeyCode.RightArrow))
{
// you want to both set the rotation and to move the ship when
// the button is down, so you need to group these two statements together.
transform.rotation = target2;
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
Quaternion target = Quaternion.Euler(0, 180, 0);
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.rotation = target;
// changed Vector3.forward to Vector3.back
transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
}
If you omit the curly braces, the compiler interprets this as an instruction to execute only the first command after the if statement if the condition is true. So your code was executing the rotation commands if the relevant keys were pressed, but was going ahead and executing the translation commands regardless of the outcome of the if statement.
Your answer
Follow this Question
Related Questions
How to : Tap and hold to go down. Double tap and hold to go down faster? 0 Answers
Swapping player's controls in game (2D) 1 Answer
Changing (swapping) users movement controls IN GAME on trigger (2D) 0 Answers
Good Solution to Physics Based Gameplay 1 Answer
2D Movement Controls Like a Dying Fly 0 Answers