In my project GameObject are moving when I press w/s/a/d buttons. But if I’ll press w + a, then it react only on the 1st button w. How to make it to react on the both of them?
public GameObject player;
public int moveSpeed = 10;
public int rotateSpeed = 100;
void Start ()
{
player = (GameObject)this.gameObject;
}
void Update ()
{
if (Input.GetKey (KeyCode.W))
player.transform.position += player.transform.forward * moveSpeed * Time.deltaTime;
else if (Input.GetKey (KeyCode.S))
player.transform.position -= player.transform.forward * moveSpeed * Time.deltaTime;
else if (Input.GetKey (KeyCode.A))
transform.Rotate (Vector3.down * Time.deltaTime * rotateSpeed);
else if (Input.GetKey (KeyCode.D))
transform.Rotate (Vector3.up * Time.deltaTime * rotateSpeed);
}
Simple, don’t use “else if”, just “if”, and the underlying function will be applied.
if (Input.GetKey (KeyCode.W))
player.transform.position += player.transform.forward * moveSpeed * Time.deltaTime;
if (Input.GetKey (KeyCode.S))
player.transform.position -= player.transform.forward * moveSpeed * Time.deltaTime;
if (Input.GetKey (KeyCode.A))
transform.Rotate (Vector3.down * Time.deltaTime * rotateSpeed);
if (Input.GetKey (KeyCode.D))
transform.Rotate (Vector3.up * Time.deltaTime * rotateSpeed);
But if don’t want conflicts when either “w+s” and “a+d” are pressed, then remove only the “else if” before KeyCode.A:
if (Input.GetKey (KeyCode.W))
player.transform.position += player.transform.forward * moveSpeed * Time.deltaTime;
else if (Input.GetKey (KeyCode.S))
player.transform.position -= player.transform.forward * moveSpeed * Time.deltaTime;
if (Input.GetKey (KeyCode.A))
transform.Rotate (Vector3.down * Time.deltaTime * rotateSpeed);
else if (Input.GetKey (KeyCode.D))
transform.Rotate (Vector3.up * Time.deltaTime * rotateSpeed);