- Home /
The question is answered, right answer was accepted
Isometric diagonal movement (not 45 degrees) in a 2D game C#
Hi, I'm trying to create an 8 direction movement script for my character in C#. I'm using the 2D mode, and my character uses a rigidbody2D.
My character script works, and allows the player to move in 8 directions. The issue is that my game is based on a isometric grid. Right now when moving diagonally, my character goes in a 45 angle. I'm having trouble thinking of a way to achieve diagonal movement that aligns with the tile's direction (30 degrees up and down from the horizontal direction). I want to keep the up, down and sideways movement, and just need to figure out how to correct the diagonals.
This section of my character controller script is running in the Update().
In the picture, the red arrows are the current 45 angle used by the character, and the green arrows are the intended path it should follow.
Thank you in advanced!
float movesides = Input.GetAxis ("Horizontal");
float moveupdown = Input.GetAxis ("Vertical");
GetComponent<Rigidbody2D>().velocity = new Vector2 (movesides, moveupdown);
GetComponent<Rigidbody2D>().velocity = GetComponent<Rigidbody2D>().velocity.normalized;
normVelocityX = GetComponent<Rigidbody2D>().velocity.x * maxSpeed;
normVelocityY = GetComponent<Rigidbody2D>().velocity.y * maxSpeed;
GetComponent<Rigidbody2D>().velocity = new Vector2 (normVelocityX, normVelocityY);
Edit: I found the solution. Added the following code after my two GetAxis lines.
If up or down is pressed at the same time as left or right (both move variables will be not equal to 0), it changes the y value to half, just like in isometric tile proportion. Not perfect movement, but I can work from here.
if (movesides != 0 && moveupdown != 0)
{
moveupdown = moveupdown/2;
}
Adding a comment for anyone looking for this after me... I also found that halving the vertical movement worked but it also makes vertical movement appear very slow. I managed to find a good solution for movement in all directions but still handling the diagonals.
The important part is halving the vertical force but clamping the overall vector (if that makes sense). This maintains the direction but doesn't reduce the speed:
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
float deltaX = horizontal != 0 ? horizontal * acceleration : 0;
float deltaY = vertical != 0 ? vertical * acceleration / 2 : 0;
Vector2 deltaVector = Vector2.ClampMagnitude(new Vector2(deltaX, deltaY), 1) * maxSpeed;
physicsBody.AddForce(deltaVector);
Follow this Question
Related Questions
Passing in animation states based on mouse clicks? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Player Momentarily Stuck at Edges of Screen! 1 Answer
Delayed response: Jumping up from ledge 0 Answers