- Home /
Another Mathf.Clamp Not Working on Rotate?
I've been trying many of the post solutions to this problem and it's just not coming together.
My input should be from the keyboard WASD. I am trying to rotate an object with those keys. I have a custom pivot point for the object, which mostly works, but I really want to clamp the rotation so that it doesn't go all wonky on me.
Right now, my code below does allow the rotation, but there's no clamp at all. It's like it doesn't see it.
Any help would be awesome, please.
public float speed = 5f;
void update () {
float moveh = Input.GetAxis("horizontal") * speed * Time.deltaTime;
float movev = Input.GetAxis("vertical") * speed * Time.deltaTime;
moveh = Mathf.Clamp(moveh, -5, 5);
movev = Mathf.Clamp(movev, -50, 50);
transform.Rotate(movev, moveh, 0);
}
Not sure what I am missing.
Answer by Munchy2007 · Oct 15, 2015 at 02:26 PM
You are clamping the amount of rotation you are adding, and not the actual rotation of the object.
This example will clamp the rotation 40 degrees either side of zero on the y axis. You should be able to modify it to suit your needs.
public float speed = 20f;
void Update () {
float moveh = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
float movev = Input.GetAxis("Vertical") * speed * Time.deltaTime;
transform.Rotate(movev, moveh, 0);
var rot = transform.rotation.eulerAngles;
if(moveh > 0 && (rot.y > 40 && rot.y < 320)) rot.y = 40;
if(moveh < 0 && (rot.y < 320 && rot.y > 40)) rot.y = 320;
transform.rotation = Quaternion.Euler(rot);
}
This may not be the best or most efficient approach, but it does work and might help you work out a better solution.
Thanks $$anonymous$$unchy, that really seemed like it would work and it was an approach I hadn't tried.
Alas, no cookie.
As an aside, whenever I use anything that called any of the Eulers it will immediately flip the game object (a weapon in this case) around to face the player the moment I try to rotate the item in game mode.
Thanks $$anonymous$$unchy, that really looked like it would work and it was an approach I hadn't tried yet, but alas.... still no cookie.
As an aside, it seems like anything that calls any Euler seems to immediately flip the weapon which is being rotated. So it ends up pointing right back at the player.... it's kind of comical.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Not able to clamp camera rotation 1 Answer
Object rotation using Mathf.Atan2 0 Answers
Trigonometry Unit Circle Question 1 Answer