Disable diagonal movement on 2D character controller

Hey,

I am trying to disable diagonal movement in a really simple 2D character controller. I have been trying all sorts of things with no real luck at all.

Basically, when two movement keys (i.e. “w” & “d”) are pressed at the same time I want the controller to ceither ontinue along the axis of whichever button was pressed first or just not move at all. Looking for something similar to 2D grid based movement without it being grid based.

Any help would be appreciated greatly.

Thanks!

var speed : float = 15;

function Update () {

	if(Input.GetButton("Vertical")) {
		transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
	}

	if(Input.GetButton("Horizontal")) {
		transform.Translate(Vector3(speed,0,0) * Time.deltaTime);
	}

	if(Input.GetButton("-Vertical")) {
		transform.Translate(Vector3(0,-speed,0) * Time.deltaTime);
	}

	if(Input.GetButton("-Horizontal")) {
		transform.Translate(Vector3(-speed,0,0) * Time.deltaTime);
	}

}

What you are doing here is writing

#breakaway code.

.

Quite simply, you forgot the “return” inside each clause. That’s what you “meant” when you were thinking about it, you just forgot to type the “return” calls. It is an exceptionally common beginner mistake.

(Note that there are huge philosophical issues relating to whether one should write “breakaway code” and for people who do things like “think of algorithms” it is a topic of obsession. Furthermore your whole approach to picking up buttons like that may be done in utterly different and perhaps better ways. But the fact is in the situation at hand you simply “forgot the returns” - that’s what you meant in your head, you wanted it to do one of those and that’s it - right?)

Hope it helps.

function Update()
	{
	if(Input.GetButton("Vertical"))
		{
		transform.Translate(Vector3(0,speed,0) * Time.deltaTime);
		return;
		}

	if(Input.GetButton("Horizontal"))
		{
		transform.Translate(Vector3(speed,0,0) * Time.deltaTime);
		return;
		}

	if(Input.GetButton("-Vertical"))
		{
		transform.Translate(Vector3(0,-speed,0) * Time.deltaTime);
		return;
		}

	if(Input.GetButton("-Horizontal"))
		{
		transform.Translate(Vector3(-speed,0,0) * Time.deltaTime);
		return;
		}

	}