- Home /
How to rotate object x degrees on 1 key press with lerpangle
I'm a newb, so bear with me. How would I go about taking an object, and rotating it smoothly (lerpangle I assume) from its current position to another angle on one axis after a single key press.
In other words, say I have a cube, and I want to press the up arrow (and release it), and then have it smoothly transition on the x axis by -10 degrees smoothly. I hope this makes sense! I tried doing it with various lerp functions, I can get this to work:
float angle = Mathf.LerpAngle (0.0f, 30.0f, Time.time); transform.eulerAngles = new Vector3 (0, angle, 0);
But if I put it inside if (Input.GetKeyDown(KeyCode.RightArrow))
Then it happens instantly. Thanks!
Answer by Maurice_B · Jan 14, 2015 at 07:23 AM
Sorry I amm no good at c# but i can give a code to you in js and you could try and convert it.
var canturn :boolean = true;//so button spamming doesnt break it
function Update(){
if (Input.GetKeyDown(Keycode.RightArrow)&&canturn){
canturn = false;
Rotate(10,1);
}
if (Input.GetKeyDown(Keycode.LeftArrow)&&canturn){
canturn = false;
Rotate(10,-1);
}
}
function Rotate(rot : int,mp : int)
{
rot = Mathf.Abs(rot);//make sure rot is positive
for (i=0;i<rot;i++)
{
transform.Rotate(Vector3(0,Time.deltaTime*mp,0));
yield;//wait 1 frame
}
canturn=true;
}
i converted it but it will not work perfectly probably.
// Converted from UnityScript to C# at http://www.$$anonymous$$2H.nl/files/js_to_c.php - by $$anonymous$$ike Hergaarden
// Do test the code! You usually need to change a few small bits.
using UnityEngine;
using System.Collections;
public class Turn : $$anonymous$$onoBehaviour {
bool canturn = true;
void Update (){
if (Input.Get$$anonymous$$eyDown($$anonymous$$eycode.RightArrow)&&canturn){
canturn = false;
Rotate(10,1);
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eycode.LeftArrow)&&canturn)
{
canturn = false;
Rotate(10,-1);
}
}
void Rotate ( int rot , int mp ){
rot = $$anonymous$$athf.Abs(rot);
for (i=0;i<rot;i++)
{
transform.Rotate(Vector3(0,Time.deltaTime*mp,0));
yield return 0;
}
canturn=true;
}
}
Interesting. I thought about using a for loop too. Thanks for the answer.
Also, after some further research, I found some info about using a Coroutine.
http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.StartCoroutine.html
I may have to experiment with this too...
Your answer
Follow this Question
Related Questions
Button Particle Emission 1 Answer
Get numeric key 4 Answers
How does unity focus GUI when different keys are pressed? 0 Answers
Trouble getting key down to work 1 Answer
GetKeyDown Enter button not working 1 Answer