- Home /
Rotating object on one axis using Input.GetAxis
I'm very new to C# and I've been reading the lessons and anything I could find here on Unity Answers. I've been failing to understand this code... not sure if I'm close or very far off.
using UnityEngine;
using System.Collections;
public class RotateTriggers : MonoBehaviour
{
public float speed = 5.0f;
void Update () {
Vector3 v3 = Vector3(0.0, Input.GetAxis("Horizontal"), 0.0);
transform.Rotate(v3 * speed * Time.deltaTime);
}
}
All I'm looking to accomplish is to use an axis control (in this case the Xbox 360 Triggers) to rotate an object smoothly on one axis (I understand that may not be strictly what is happening).
Any help appreciated (if I'm going about this completely the wrong way, please feel free to change my approach).
Answer by robertbu · Apr 13, 2014 at 01:25 AM
When posting a question, please explain what is going on, and what is your desired behavior. For example I can see the code above would not compile, so including the compiler error messages (copied directly from the console) is really helpful in getting to an answer. As for your code, you can simplify it to:
using UnityEngine;
using System.Collections;
public class RotateTriggers : MonoBehaviour {
public float speed = 5.0f;
void Update () {
transform.Rotate(0.0f, -Input.GetAxis ("Horizontal") * speed, 0.0f);
}
}
Note in this case, you don't need to use Time.deltaTime since that is factored to some degree by the value return by Input.GetAxis().
Thank you for the note on Time.deltTime. I really didn't consider the relevence of the axis position... very cool.
While waiting for an answer on this I was getting even more lost trying to get this working with Quaternion.Euler which, while interesting, turned out to be the wrong choice here. I can tweak the rest from the Input settings as far as sensitivity and speeds go.
(and duly noted about the compile error. I will be sure to be more detailed and provide such details in the future)
Appreciated!
Transform.Rotate() is a relative rotation that is in local space. Transform.eulerAngles is a absolute rotation in world space. You could do something similar to the code above using eulerAngles like this:
using UnityEngine;
using System.Collections;
public class RotateTriggers : $$anonymous$$onoBehaviour
{
public float speed = 5.0f;
private float rot = 0.0f;
void Update () {
rot -= Input.GetAxis ("Horizontal") * speed;
transform.eulerAngles = new Vector3(0.0f, rot, 0.0f);
}
}
I may have dismissed the use of 'deltaTime' too quickly. It depends on what is tied to the "Horizontal" axis. If it is a button, then you would want to use deltaTime (and you would have to substantially increase 'speed').
after i turn it, even tho im not pressing the button, it still continue turning. how can i fix that?