- Home /
How do I set the maximum wheel rotation on my car?
When I click the to button the wheel spins clockwise to 25 degrees which is correct. But when I click "a" nothing happens. When I change to a negative value the wheels keep spinning forever, what can I do?
void Update()
{
Debug.Log(transform.eulerAngles.y);
if ((Input.GetKey("a")) && (transform.eulerAngles.y > 335))
{
transform.Rotate(-Vector3.up * speed * Time.deltaTime);
}
if ((Input.GetKey("d")) && (transform.eulerAngles.y < 25))
{
transform.Rotate(Vector3.up * speed * Time.deltaTime);
}
}
}
Answer by jackmw94 · Nov 10, 2020 at 09:44 PM
The problem here is that 360 is also 0 degrees, 270 degrees is also -90 degrees, etc. This means that whenever we want to find the differences between angles in degrees we have to account for these possible offsets. Luckily, unity provides us with functions to help!
if (Input.GetKey(KeyCode.A)
&& Vector3.SignedAngle(Vector3.forward, transform.forward, Vector3.up) > -25f)
{
transform.Rotate(-Vector3.up * (speed * Time.deltaTime));
}
if (Input.GetKey(KeyCode.D)
&& Vector3.SignedAngle(Vector3.forward, transform.forward, Vector3.up) < 25)
{
transform.Rotate(Vector3.up * (speed * Time.deltaTime));
}
This will mean that A will work while its forward direction is less than 25 degrees anti-clockwise from forward and D will work while forward is less than 25 degrees clockwise of it.
This is a good starting point to demonstrate the angle issue but there will be a problem here given the fact we are comparing to the global forward direction - thus breaking this if you ever want to turn your car, which I think you might.
To solve this we should compare to the car's forward direction.
Vector3 carForwardDirection = carTransform.forward;
Vector3 carUpDirection = carTransform.up;
if (Input.GetKey(KeyCode.A)
&& Vector3.SignedAngle(carForwardDirection , transform.forward, carUpDirection ) > -25f)
{
transform.Rotate(-carUpDirection * (speed * Time.deltaTime));
}
if (Input.GetKey(KeyCode.D)
&& Vector3.SignedAngle(carForwardDirection , transform.forward, carUpDirection ) < 25)
{
transform.Rotate(carUpDirection * (speed * Time.deltaTime));
}
It's hard to test code snippets so I haven't but I hope this either works or helps!
A few side notes, I've added the brackets in side the rotate call to ensure that we multiply floats before the vector, multiplying my a vector is marginally more expensive than floats, so this way we only do it once. Won't make a big difference but it's a good habit. Also I changed the "a" to KeyCode.A, it's a little nicer to use the enum as it prevents typos - probably hard to do for a single letter but you never know!
Your answer
Follow this Question
Related Questions
Procedurally generate a car track 1 Answer
Accelerate and brake a car without wheel collider 1 Answer
Help with AI car physics 1 Answer