Basic character movement, GetAxis and GetButton

Hi!

Seems like the prefered method to set character controls is through Input.GetAxis. I can obviously see its benefits, it makes it so easy to write the controls for a number of devices. Unfortunately, the fact that it checks for an axis instead of 4 directions seems to make it a bit sloppy for the keyboard.

If a player pressed the left and right key at the same time, for example, there IS axis input but the character shouldn’t be moving.

I would like to know if there would be a way to have more control over the keyboard input while keeping the ease of having a function controlling the movement for any kind of device.

So, instead of:

GetAxis("Horizontal")

you would use :

var x = Mathf.Clamp(
	((GetButton(KeyCode.D) ? 1.0 : 0.0) - (GetButton(KeyCode.A) ? 1.0 : 0.0)) +
	((GetButton(KeyCode.RightArrow) ? 1.0 : 0.0) - (GetButton(KeyCode.LeftArrow) ? 1.0 : 0.0)) +
	... next form of movement
	,-1.0, 1.0);

Thanks :slight_smile:

I finally got it to work, my code is like this:

		Vector3 charDirection = new Vector3 (0,0,0);
		
		if (Input.GetButton("moveRightKB")) {
			charDirection.x += 1;
		}
		if (Input.GetButton("moveLeftKB")) {
			charDirection.x -= 1;
		}
		if (Input.GetButton("moveUpKB")) {
			charDirection.y += 1;
		}
		if (Input.GetButton("moveDownKB")) {
			charDirection.y -= 1;
		}
		charDirection.Normalize();
							 
		transform.position = new Vector3 (	transform.position.x + charDirection.x * charSpeed * Time.deltaTime,
							transform.position.y + charDirection.y * charSpeed * Time.deltaTime,
							0);

This way the cube doesn’t move when 2 opposing keys are pressed. The Normalize function makes it have a better diagonal speed, too.