- Home /
How can I make an object rotate to a specific euler angle?
Essentially, what I'm trying to accomplish is I want a character to rotate in the direction he will be moving. So if the player holds the move up key, the character will start moving forward as he rotates to that direction.
So the way I've theorized this is that the character will rotate to a set y-axis euler angle. So, in the case of up, 270, right would be 0, and so on. The way I'm doing this right now I feel is a bit inefficient, and doesn't allow for diagonal movement, either:
else if (Input.GetKey(KeyCode.W))
{
if ((transform.eulerAngles.y > 270f && transform.eulerAngles.y <= 360f) || (transform.eulerAngles.y >= -.5f && transform.eulerAngles.y <= 90f))
transform.Rotate(new Vector3(0, -rotSpeed, 0));
transform.position += (transform.forward * moveSpeed * Time.deltaTime);
}
If this seems too vague, let me know and I'll attempt to clarify. While my code is in C#, I'm fine with solutions both that and JavaScript. Thanks!
Answer by fueldown · Jun 03, 2013 at 06:25 PM
float currentRotation = transform.rotation.eulerAngles.y;
if (Input.GetKey(KeyCode.W))
{
transform.Rotate(new Vector3(0f, -rotSpeed * Time.deltaTime, 0f));
currentRotation = Mathf.Clamp(currentRotation, -90f, 90f);
transform.position += (transform.forward * moveSpeed * Time.deltaTime);
}
Will this do it for you? I am not sure what type of game you are making, but from description, I am assuming it is a side scroller. I hope this helps.
Thanks. The game I'm making is a 3D platformer. The code you provided didn't work, but perhaps I'm not understanding it correctly.
From what I can see, in this case, when the user is pressing the W key, the game will rotate the object at the rotate speed scaled by deltaTime about the Y axis, and then currentRotation is clamped to the range of -90 to 90 degrees?
Your answer
Follow this Question
Related Questions
How to Make animation Playable? 1 Answer
Changing Animation Rotation offset 0 Answers
Make the character face the direction he is moving? 2 Answers
Making sprites just rotate and not tilt. 3 Answers
Unity Animation Import very slow 4 Answers