- Home /
Question by
kollosuss13 · Feb 06, 2020 at 06:48 PM ·
c#scripting problemrotate
[HELP] How to smoothly rotate camera 180 degrees on key enter?
Hello, i want to rotate camera from 0 to 180 degrees when i press W for example and when i press again it's rotates to 360. I have a script but i only did one time rotate. Please help. Script below
using UnityEngine;
using System.Collections;
public class RotChange : MonoBehaviour {
float rot_duration = 500F;
float rot_speed = 0.25F;
Quaternion final_rot;
// Use this for initialization
void Start () {
Vector3 initial_rot = transform.rotation.eulerAngles;
final_rot = Quaternion.Euler(new Vector3(initial_rot.x,initial_rot.y,180));
}
IEnumerator rotateOBJ ()
{
float rot_elapsedTime = 0.0F;
while (rot_elapsedTime < rot_duration)
{
transform.rotation = Quaternion.Slerp(transform.rotation,final_rot,rot_elapsedTime);
rot_elapsedTime += Time.deltaTime*rot_speed;
yield return null;
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("w")) StartCoroutine("rotateOBJ");
}
}
Comment
Answer by unity_ek98vnTRplGj8Q · Feb 06, 2020 at 06:59 PM
It's because you only calculate your final rotation once at the start. If you want to rotate 180 degree's every time you press the key, do something like this
using System.Collections;
using UnityEngine;
public class RotChange : MonoBehaviour {
float rot_duration = 500F;
float rot_speed = 0.25F;
Quaternion final_rot;
// Use this for initialization
void Start () {
final_rot = transform.rotation;
}
IEnumerator rotateOBJ () {
final_rot = final_rot * Quaternion.Euler (0, 0, 180);
float rot_elapsedTime = 0.0F;
while (rot_elapsedTime < rot_duration) {
transform.rotation = Quaternion.Slerp (transform.rotation, final_rot, rot_elapsedTime);
rot_elapsedTime += Time.deltaTime * rot_speed;
yield return null;
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("w")) StartCoroutine ("rotateOBJ");
}
}
Thanks! But with every rotation speed getting bigger, whats wrong?
Why do you have both a rotation speed and a rotation duration? If you want your rotation to take rot_duration time to complete do
transform.rotation = Quaternion.Slerp (transform.rotation, final_rot, rot_elapsedTime/rot_duration);
rot_elapsedTime += Time.deltaTime;
If you want your rotation to rotate according to the speed variable use
transform.rotation = Quaternion.Slerp (transform.rotation, final_rot, rot_speed*Time.deltaTime);
still rotation's speed getting bigger with every rotation
Your answer
