DISCLAIMER:
While I encourage the use of more advanced controls in this game, I do not encourage you copying and pasting this code just to get through the course. I learned a LOT in the few hours it took to build this, so please do build your own controller or take time to understand what I’m doing here. You’re only hurting yourself if you just copy and paste.
So, when challenged… I, of course, went WAY too far with the PlayerController script… but I got it working, and it works well.
using UnityEngine;
using System.Collections;
using System.Security.Cryptography;
public class PlayerController : MonoBehaviour {
bool leftPress = false;
bool rightPress = false;
bool upPress = false;
bool downPress = false;
bool firePress = false;
public float speed = 1.0f;
// Update is called once per frame
void Update ()
{
//left & right controller start
if (Input.GetKey (KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
leftPress = true;
} else {
leftPress = false;
}
print (leftPress);
if (Input.GetKey (KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
rightPress = true;
} else {
rightPress = false;
}
print (rightPress);
// left & right controller end
// up & down controller start
if (Input.GetKey (KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) {
upPress = true;
} else {
upPress = false;
}
print (upPress);
if (Input.GetKey (KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) {
downPress = true;
} else {
downPress = false;
}
print (downPress);
// up & down controller end
//fire control start
if (Input.GetKey (KeyCode.Space) || Input.GetKey (KeyCode.RightControl)) {
firePress = true;
} else {
firePress = false;
}
print (firePress);
//fire control end
MoveShip ();
}
void MoveShip ()
{
if (leftPress) {
this.transform.position += new Vector3 (-speed, 0, 0);
print ("Move Left");
}
if (rightPress) {
this.transform.position += new Vector3 (speed, 0, 0);
}
if (upPress) {
this.transform.position += new Vector3 (0, speed, 0);
}
if (downPress) {
this.transform.position += new Vector3 (0, -speed, 0);
}
}
}
The fire control is built in because I figure, eventually, I’ll need to shoot stuff. It doesn’t do anything yet, but the move keys fully function and the ship can be controlled with both wasd and arrow keys.
In my research, I did see a few posts about how to control players being able to double their speed output if they use both keys, and I have not guarded against that in any way, so you may need to consider that.
Hope this helps someone.
EDIT: Also, I’m not quite sure why my code includes:
using System.Security.Cryptography;