Simple Topdown Movement Problem

Hello,

I’m fairly new to Unity and Javascript but I’m trying to make a simple topdown game with Unity set to 2D.

Now I made this code for moving over the X and Y axis but when I run the game the player is only able to walk right and down.

 #pragma strict
    
    function Start () {
    
    }
    
    var moveLeft: KeyCode;
    var moveRight: KeyCode;
    var moveUp: KeyCode;
    var moveDown: KeyCode;
    
    var hspeed = 5;
    var vspeed = 5;
    
    
function FixedUpdate () {
    
    	if (Input.GetKey(moveLeft))
    	{
    		rigidbody2D.velocity.x = -hspeed;
    	}
    	else
    	{	
    		rigidbody2D.velocity.x = 0;
    	}
    	
    	if (Input.GetKey(moveRight))
    	{
    		rigidbody2D.velocity.x = hspeed;
    	}
    	else
    	{	
    		rigidbody2D.velocity.x = 0;
    	}
    
    	if (Input.GetKey(moveUp))
    	{
    		rigidbody2D.velocity.y = vspeed;
    	}
    	else
    	{
    		rigidbody2D.velocity.y = 0;
    	}
    	
    	if (Input.GetKey(moveDown))
    	{
    		rigidbody2D.velocity.y = -vspeed;
    	}
    	else
    	{
    		rigidbody2D.velocity.y = 0;	
    	}
    }

Does anyone know where it goes wrong?

Thanks in advance

Basically by your logic which you wrote, it checks if left key is pressed, set its velocity to move sideways, but then in the next if statement, it finds that the right key is NOT pressed, it sets it back to 0 again, therefore removing what you just added prior. I suggest using If/Else statements for Left / Right and Up / Down, or even better, make use of this:

Input.GetAxis(“Horizontal”);

and

Input.GetAxis(“Vertical”);

and set the velocity to these values * your speed or something.