- Home /
Smooth 90 degree rotation on Z axis on button press
Hello! So, I have some code that does almost exactly what I want it to do (see title), but it is rotating on the X axis, and I would like it to rotate on the Z axis. I thought this would be a simple fix, but I am stumped. Any help is much appreciated!
Here is the code:
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour
{
public float smooth = 1f;
private Quaternion targetRotation;
void Start ()
{
targetRotation = transform.rotation;
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space)) {
targetRotation *= Quaternion.AngleAxis (90, Vector3.up);
}
transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation, 10 * smooth * Time.deltaTime);
}
}
I'm not sure what the C axis is, but you are rotating using the Vector3.up (world up / y vector). If you want the world Z axis, use Vector3.forward, and if you want the object's local forward, use transform.forward.
transform.forward was exactly what I needed- thank you much!!!
By the way, by "C axis", I totally meant "X axis". $$anonymous$$y bad!
hello there my friend, actually your code works perfectly on what I need I just modified this part
targetRotation = Quaternion.AngleAxis (90, Vector3.up); to this targetRotation = Quaternion.AngleAxis (90, Vector3.forward);
and it is working perfectly on $$anonymous$$d.
what it does to my modification is when I press down or tap the screen my circle or like a wheel object rotates 90 degrees smoothly.
Hope this helps
Answer by HawkSandwich · Jun 17, 2017 at 10:27 AM
Maybe after you set targetRotation, you could do this:
targetRotation = Quaternion.Euler (targetRotation.eulerAngles.x-90, targetRotation.eulerAngles.y,
targetRotation.eulerAngles.z+90);
or something similar?
Answer by Kauppasarvi · Jun 17, 2017 at 10:55 AM
Hello, you need to change axis in Quaternion.AngleAxis, like this:
if (Input.GetKeyDown (KeyCode.Space)) {
targetRotation *= Quaternion.AngleAxis (90, Vector3.forward);
}
Vector3 has some handy built-in directions, like up, forward and right. You can also define your own axises by saying like:
if (Input.GetKeyDown (KeyCode.Space)) {
targetRotation *= Quaternion.AngleAxis (90, new Vector3 (1, 2, 1));
}