- Home /
How to Rotate Game Object in specific Angle repeatedly on Key Press?
Ok, so I am trying to rotate an Equilateral Triangle in Y-Axis. So basically I want this Triangle to rotate +120 degrees everytime I press the key "W" and -120 degrees every time I press the Key "S".
Answer by Casy10 · Sep 08, 2017 at 08:35 AM
Hello @manikiran22 ! Hope this helps you :
using UnityEngine;
public class FixedAngleRotator : MonoBehaviour
{
public float XAngle;
public float YAngle;
public float ZAngle;
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
transform.Rotate(XAngle, YAngle, ZAngle);
if (Input.GetKeyDown(KeyCode.S))
transform.Rotate(-XAngle, -YAngle, -ZAngle);
}
}
$$anonymous$$an thanks @Casy10 a ton it is rotating as I wanted it to :) , one thing i want to implement is the triangle is rotating fine but is there a way to see its rotation smoothly like i want the user to see the triangle rotate +120 or -120 degrees. thanks again :)
I may be able to help, what do you mean by wanting the user to see it rotate +120 or -120 degrees? Do you want it to instantly turn that much or slowly rotate until it has turned 120 degrees?
@manikiran22 This will do what you want nicely, I think.
using UnityEngine;
using System.Collections;
public class FixedAngleRotator : $$anonymous$$onoBehaviour
{
public Vector3 EulerRotation = new Vector3(0f, 120f, 0f);
public float TimeToRotate = .5f;
private bool rotating;
private void Update()
{
if (!rotating)
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W))
{
StartCoroutine(doRotate(EulerRotation));
}
else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.S))
{
StartCoroutine(doRotate(-EulerRotation));
}
}
}
private IEnumerator doRotate(Vector3 rotation)
{
Quaternion start = transform.rotation;
Quaternion destination = start * Quaternion.Euler(rotation);
float startTime = Time.time;
float percentComplete = 0f;
rotating = true;
while(percentComplete <= 1.0f)
{
percentComplete = (Time.time - startTime) / TimeToRotate;
transform.rotation = Quaternion.Slerp(start, destination, percentComplete);
yield return null;
}
rotating = false;
}
}
I don`t understand why you multiply the two Quaternion Quaternion destination = start * Quaternion.Euler(rotation); It`s working prefect without this multiplication.
But what is mean that? percentComplete = (Time.time - startTime) / TimeToRotate;