# 2D diagonal movement using Rigidbody2D

I have a problem with 2d player movement, as I am unable to move on the Y-axis. Yet, the movement on the X-axis is working as intended.

Below, you can see my code:

public Sprite directionUp;
public Sprite directionDown;
public Sprite directionLeft;
public Sprite directionRight;

public float speed = 0.1f;
public byte direction = 0; //0 - up, 1 - right, 2 - down, 3 - left

private SpriteRenderer spriteRenderer;
private Rigidbody2D rb2D;
private Sprite[] directionArray;

// Use this for initialization
void Start () {
rb2D = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();

directionArray = new Sprite[]{ directionUp, directionDown, directionLeft, directionRight };
if(directionArray[0] != null) spriteRenderer.sprite = directionArray[0];
}

// Update is called once per frame
void Update ()
{
{
rb2D.MovePosition(rb2D.position + new Vector2(-1f, 1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(1f, 1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(-1f, -1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(1f, -1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(0f, 1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[0];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(0f, -1f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[1];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(-1f, 0f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[2];
}
{
rb2D.MovePosition(rb2D.position + new Vector2(1f, 0f));

if (directionArray[0] != null) spriteRenderer.sprite = directionArray[3];
}
}


By the way, please keep in mind I am quite new to Unity.

EDIT 1///////////////////////

I have attached the entire script, some of the variables are unused right now(was testing other methods of movement).

I tried to both Keypad - 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off-topic and I will look into it once I will get the Y-axis to move).

Thanks, Zryw

• Put the whole script. – Sourav Paul Roman Jul 16 '16 at 22:28
• Are you trying to go diagonal by holding two keys at once, or by pressing some seperate "diagonal motion" key – bpgeck Jul 16 '16 at 23:24
• Don't edit solutions to your question. Instead, just post the solution as an answer, and don't forget to accept it. – Tyyppi_77 Jul 17 '16 at 11:25
• Thanks for your input, I posted the answer as you suggested. – zryw141 Jul 17 '16 at 11:30