Making a character rotate diagonal?

Hi I’m trying to get my character to rotate 45 degrees in the y euler. The character can run in the x and z axis, so its got the right y euler angle for them. What i want is to rotate to 45 degress whenever the character goes both in the x and z axis.

im very new to scripting so i cant really wrapped my head around this.

function Update () 

{
//rotate in horizontal and vertical planes

if (Input.GetKeyDown("d") && !(Input.GetKeyDown("w")))
	{
		transform.eulerAngles.y = 90;
	}
if (Input.GetKeyDown("a"))
	{
		transform.eulerAngles.y = 270;
	} 
if (Input.GetKeyDown("w") && !(Input.GetKeyDown("d")))
	{
		transform.eulerAngles.y = 0;
	}
if (Input.GetKeyDown("s"))
	{
		transform.eulerAngles.y = 180;
	}
//rotate in diagonal planes
if (Input.GetKeyDown("w") && Input.GetKeyDown("d"))
	{
		transform.eulerAngles.y = 45;
	}

}

You don’t have to be fixed on 45 degree increments, its pretty easy.

function Update () 
{
    var hor = Input.GetAxis("Horizontal"));
    var ver = Input.GetAxis("Vertical"));

    // Depends on the default facing direction, which is usually the character facing forward z axis
    if(hor < 0)
       transform.eulerAngles.y = Vector2.Angle(Vector2(0,1), Vector2(hor, ver));
    else if(hor > 0)
       transform.eulerAngles.y = -Vector2.Angle(Vector2(0,1), Vector2(hor, ver));
    // ignore when hor = 0
}

You’ll get what I did if you’ve done some basic Vector algebra. If you didn’t, I’ll give a brief explanation:


Imagine there’s a 2d plane(X and Y axes) on the floor and character is standing on it. The characters faces this imaginary Y axis and his right hand faces the X axis.


The angle between a reference point (1,0) and the user inputs on the horizontal and vertical axes is the angle your character should be facing.
I’m assigning the negative angle when its obtuse( > 180) because Vector2.Angle() always returns the smallest angle which is always < 180

Hope you find this useful