- Home /
How to rotate sphere when moving in Unity
Hey all,
I have a sphere GameObject with a character controller on it. I want the sphere to rotate as if it's rolling when I move the character.
I came up with a way to do it by making the sphere rotate when the WASD keys are pressed, but now I am mapping a Playstation controller to my character and it's no longer rotating when I move with the joystick (because WASD is not being input)...
Does anyone know a way to make a sphere rotate when "Horizontal" or "Vertical" Inputs are being received in Unity? Here is my current code which works for WASD keys but not the PS4 controller:
void RotateSphere () { transform.Rotate (Vector3.right, rotateSpeed * Time.deltaTime);}
void Movement () {
if (Input.GetKey (KeyCode.W)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.A)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.D)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.S)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.UpArrow)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.LeftArrow)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.RightArrow)) {
RotateSphere ();
} else if (Input.GetKey (KeyCode.DownArrow)) {
RotateSphere ();
}
void Update (){
//this runs the Movement simulation on Update
Movement ();
}
Answer by Ginxx009 · Dec 11, 2017 at 06:56 AM
You can do it something like this
public Transform from;
public Transform to;
public float speed = 0.1F;
public void RotateSphere(){
transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);
}
Use a Quaternion.Lerp
because it is much faster and good looking that .slerp.
function