- Home /
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;
}
}
Answer by jorjdboss · Jun 25, 2012 at 12:01 PM
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
Thank you for that detailed answer, very useful indeed. With a few bits of tweaking it works better than what I wanted. Never thought about using input getaxis and vector2 that way. :)
Glad to know you found my explanation useful. Unity has more such tricks people aren't aware about or forget. I'd say get a good grip on the documentation and you're golden! This is my way of doing it, there might be other ways of doing it without using vector2, go figure :) It'd be nice if you gave a vote up(my first vote!)
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How do I invert the Y axis in Penelope tutorial? 3 Answers
Joystick ellipse movement (2d mobile asset modification) 1 Answer