Day 89 — Updating Player Rotaion in a 2.5D Environment

Hey and welcome!

Nice short one here going over how to tweak our code and make the character turn to the left when they’re moving in that direction.

Luckily it’s nice and easy with this bit of code:

void Update()
{
if (_controller.isGrounded == true)
{
float horizontalInput = Input.GetAxis("Horizontal");
_direction = new Vector3(horizontalInput, 0, 0);
if (horizontalInput != 0)
{
Vector3 facing = transform.localEulerAngles;
facing.y = _direction.x > 0 ? 0 : 180;
transform.localEulerAngles = facing;
}
}
}

The value horizontalInput will be 1, -1 or 0 depending on the inputs that have been done. If the D key is pressed this value will be 1, if the A key is pressed then the value will be -1 and if no key is pressed this value is 0. So when we check if horizontalInput does not equal 0 then this bit of code will run every frame when the player is moving.

We’re then creating a local Vector3 variable for the local euler angles in order to implement rotation on the y axis. There’s something a little new in here as well which is this line facing.y = _direction.x > 0 ? 0 : 180. The first part is easy enough as you can see that we’re going to be assigning sometthing to the y value of facing. The next bit is where it gets interesting, it’s best to think of what’s happening as a self contained if/else statement so I’ll describe it in order.

If _direction.z is greater than 0 then the value is 0, else the value is 180. So the value that we assign to facing.y is either going to be 0 or 180 depending if _direction.x is -1 or 1 which is our key presses.

Once we have that we finish off by assigning the value of facing to the local euler angles for the character so that they stay in the direction they’re facing even when they’re not moving, whether that’s facing to the left or right.

It’s a pretty cool bit of code and now makes the game look a bit more realistic:

That’s everything sorted now with our idle, running and jumping animations adn it ended up being quite a bit to cover! Next time we’ll be looking into implementing a ledge grabbing mechanic into the game.

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.