# How to prevent diagonal movement on 2d-rigidbody script?

Hello!

I have this script, attached to a simple cube player, and it is working well, detecting collision and objects (thanks to rigid body).
Problem is that i cannot manage to let him move “just” one direction… I mean, if i press another key while moving, the movement is diagonal, instead i would like to have him stopping one direction and only enabling the new one.

If someone can help me, i would really appreciate!

``````    #pragma strict

//how fast the player walks
var walkSpeed:float = 14.0;

function Update () {

if(Input.GetKey("a") || Input.GetKey("d") || Input.GetKey("left") || Input.GetKey("right"))
{

if(Input.GetKey("a") || Input.GetKey("left"))
{
if(rigidbody.velocity.x > 0)
{
rigidbody.velocity.x = 0;
}
if(rigidbody.velocity.x > -walkSpeed)
{
rigidbody.velocity.x -= 48*Time.deltaTime;
}
}

if(Input.GetKey("d")|| Input.GetKey("right"))
{
if(rigidbody.velocity.x < 0)
{
rigidbody.velocity.x = 0;
}
if(rigidbody.velocity.x < walkSpeed)
{
rigidbody.velocity.x += 48*Time.deltaTime;
}
}

}
else
{

rigidbody.velocity.x = 0.0;
}
if(Input.GetKey("w") || Input.GetKey("s") || Input.GetKey("up") || Input.GetKey("down"))
{

if(Input.GetKey("s") || Input.GetKey("down"))
{
if(rigidbody.velocity.z > 0)
{
rigidbody.velocity.z = 0;
}
if(rigidbody.velocity.z > -walkSpeed)
{
rigidbody.velocity.z -= 48*Time.deltaTime;
}
}

if(Input.GetKey("w")|| Input.GetKey("up"))
{
if(rigidbody.velocity.z < 0)
{
rigidbody.velocity.z = 0;
}
if(rigidbody.velocity.z < walkSpeed)
{
rigidbody.velocity.z += 48*Time.deltaTime;
}
}

}
else
{

rigidbody.velocity.z = 0.0;

}

}
``````

Ps: i’m learning Unity and C#, though i found the script among a js compilation… If someone could help me translate this also, it would be a really nice favor!

You can put lines 42 - 67 just below line 40 in the ‘else’ clause. This will eliminate diagonal movement, but it gives dominance to horizontal movement. That is if a vertical and a horizontal key are pressed, your character will move horizontally.

It is fairly complex to recode this so that the first key (horizontal or vertical) is what is done. You can switch the logic and embed the horizontal in the else clause of the vertical if you wanted to give vertical preference.

Just click the button in the inspector …

look at the rigidbody in the Inspector in the editor.