Hey guys,
I’m currently studying GameProgramming, and I’d love to learn the best ways in how to program.
If l’m going to make huge games in the future, every single microsecond matters.
Just for a character moving left and right, you can program it in loads of different ways, but which one is the best…?
For example, I can use this to change the direction:
private int dir;
private int left = 0;
private int right = 0;
void Update ()
{
if (Input.GetKey(KeyCode.A))
{
left = 1;
}
else
{
left = 0;
}
if (Input.GetKey(KeyCode.D))
{
right = 1;
}
else
{
right = 0;
}
dir = right - left;
}
But I can also use this:
private int dir;
private int left = 0;
private int right = 0;
void Update ()
{
if (Input.GetKeyDown(KeyCode.A))
{
left = 1;
}
if (Input.GetKeyDown(KeyCode.D))
{
right = 1;
}
if (Input.GetKeyUp(KeyCode.A))
{
left = 0;
}
if (Input.GetKeyUp(KeyCode.D))
{
right = 0;
}
dir = right - left;
}
Or this:
private int dir;
private bool left = false;
private bool right = false;
void Update ()
{
left = Input.GetKey(KeyCode.A);
right = Input.GetKey(KeyCode.D);
if (right !left)
{
dir = 1;
}
else if (left !right)
{
dir = -1;
}
else
{
dir = 0;
}
}
Or I can use just this small piece of code:
private int dir;
void Update ()
{
dir = System.Convert.ToInt16(Input.GetKey(KeyCode.D)) - System.Convert.ToInt16(Input.GetKey(KeyCode.A));
}
And of course there are many other ways to do it, but which one is the best…?
Yeah, the last one is shorter in code, but every time it runs the Update, it has to Convert a bool to an integer.
And I could just use “Input.GetKey”, but every single time it has to set an integer to a certain value, otherwise it can just skip it, and only when something changes, set the integer.
Is there anyone that knows what the best way to use is? And are there any sites with explanations about these matters?
~DamnICantFly~