# Unity 2D, C# - Make object move diagonally by a certain angle?

I have a sprite object which I want to move in 8 directions. Left, Right, Up, Down, Left top, Right top, Left down, Right down. The view is 2D with a isometric projection. The difficulties I am having is when the object needs to move diagonally. I need to work out how I can move the sprite in fixed degrees diagonally so its parallel to the isometric world.

I have a diagram to demonstrate. Here the green arrows are the diagonal movement that I need. The code I have for up, down, left and right movement is already in,

void FixedUpdate ()
{

speed = 10f;
//pos = Camera.main.ViewportToWorldPoint (new Vector3 (0.5F, 0.5F, Camera.main.nearClipPlane));
//transform.position = new Vector3 (pos.x, pos.y, -1F);

if (Input.GetKey (KeyCode.D)) {
rigidbody2D.velocity = Vector2.right * speed;

} else if (Input.GetKey (KeyCode.A)) {
rigidbody2D.velocity = -Vector2.right * speed;
} else if (Input.GetKey (KeyCode.S)) {
rigidbody2D.velocity = -Vector2.up * speed;
} else if (Input.GetKey (KeyCode.W)) {
rigidbody2D.velocity = Vector2.up * speed;
} else {
rigidbody2D.velocity = Vector2.zero;
}
}


I had a look at the Transform class and the various variables and functions but I don't know what to use or start with. This is because I am very new to Unity and maths such as rotations, axis, etc. So a helping direction would be massively appreciated. Thanks.

• Instead of using if/else to capture input why not capture all inputs in a frame and use a temporary variable (say a vector2) to store the summation of those inputs? Aug 30 '14 at 23:38
• @Dialock sorry you would have to give me a small code example in order for me to fully understand what your on about. Aug 30 '14 at 23:48

//temp helper variable
var moveAmount = Point.Zero;

if (InputHandler.KeyPressed(Keys.A) || InputHandler.KeyPressed(Keys.Left))
moveAmount.X -= 1;
if (InputHandler.KeyPressed(Keys.D) || InputHandler.KeyPressed(Keys.Right))
moveAmount.X += 1;
if (InputHandler.KeyPressed(Keys.W) || InputHandler.KeyPressed(Keys.Up))
moveAmount.Y -= 1;
if (InputHandler.KeyPressed(Keys.S) || InputHandler.KeyPressed(Keys.Down))
moveAmount.Y += 1;
// do stuff
rigidbody2D.velocity = moveAmount * speed;