- Home /
Rotating a character smoothly around 90 degrees
Hi I'm working on my first game, a top down 2D game. I need the player to rotate smoothly 90 degrees around the local y axis over half a second. At the moment I am using
GameObject.Find("Player").transform.Rotate(Vector3(0, 90, 0));
which rotates the character fine, but instantly rather than smoothly over around half a second as I need it to. I have tried using Time.deltaTime but when used the character rotates a small amount rather than the full 90 degrees.
Here's all I have so far
private var canMove : boolean;
function Start () {
canMove = true;
}
function Update () {
if(canMove){
if(Input.GetKeyDown("left")){
TurnLeft();
}
if(Input.GetKeyDown("right")){
TurnRight();
}
}
}
function TurnLeft () {
GameObject.Find("Player").transform.Rotate(Vector3(0, 90, 0));
}
function TurnRight () {
GameObject.Find("Player").transform.Rotate(Vector3(0, -90, 0));
}
This might be completely wrong but I am extremely new to coding still. Hope you can help.
First of all. Never use .Find("nameOfObject") in something called through the Update-function. As .Find searches through all objects in the scene. You could instantiate it as a variable in function Start().
This is however not related to your question.
Okay, it's still useful though, thank you for the advice!
Answer by DeveshPandey · Nov 28, 2012 at 07:04 AM
Try this :
private var canMove : boolean;
private var turnLeft : boolean;
private var turnRight : boolean;
private var rotationVal : float = 0f;
private var temp : float = 0f;
private var myTransform;
function Start () {
canMove = true;
myTransform = GameObject.Find("Player").transform;
}
function Update () {
if(canMove){
if(Input.GetKeyDown("left")){
turnLeft = true;
//TurnLeft();
}
if(Input.GetKeyDown("right")){
turnRight = true;
//TurnRight();
}
}
}
function LateUpdate()
{
if(turnLeft)
{
if(temp > 90){
turnLeft = false;
temp = 0f;
}
else{
rotationVal = Mathf.Lerp(0f,90f,Time.deltaTime);
myTransform .Rotate(Vector3(0, rotationVal, 0));
temp += rotationVal;
}
}
else if(turnRight)
{
if(temp < -90){
turnRight = false;
temp = 0f;
}
else{
rotationVal = Mathf.Lerp(0f,-90f,Time.deltaTime);
myTransform .Rotate(Vector3(0, rotationVal, 0));
temp += rotationVal;
}
}
}
please make a vote up, to show the perfect one! thanks!
Answer by Maulik2208 · Nov 27, 2012 at 10:30 AM
Hope This will work for you.....it's works for me....
transform.Rotate(new Vector3(0, rotSpeed * Time.deltaTime, 0));
here define rotspeed to as per your requirement just like int rotSpeed = x;
IF you found this useful then let others know that click the Thumb-up symbol and tick mark as correct answer....it will help others to find out the things properly....Thanks...
I still found this soultion had the same problem, it started incresing towards 90 degrees but stopped very quickly