- Home /
Rotating an object only a set amount of degrees
I have an object rotating continuously left/right, and would like to only have it rotate 50 degrees in each direction then stop. Is there a way to accomplish this?
Here is my current code:
var speed : float;
var lerpSpeed : float;
private var xDeg : float;
private var yDeg : float;
private var fromRotation : Quaternion;
private var toRotation : Quaternion;
var cube1 : GameObject;
var rearSightLayer : int = (1 << 15);
function Update () {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit, Mathf.Infinity, rearSightLayer) && hit.transform.tag == "RearSight3")
{
if(Input.GetMouseButton(0))
{
xDeg -= Input.GetAxis("Mouse Y") * speed;
fromRotation = transform.rotation;
toRotation = Quaternion.Euler(xDeg,0,0);
cube1.transform.rotation = Quaternion.Lerp(fromRotation,toRotation,Time.fixedTime * lerpSpeed);
}
}
}
Answer by IgnoranceIsBliss · Aug 18, 2014 at 01:18 AM
You should make sure that your input to ANY interpolation function (lerp/slerp/smoothstep) is between 0 and 1. Yours will just keep going up and up, so you'd only ever move your head in one direction and it will stay there forever.
Something like
float Amnt = Time.time / TotalTravel;
Quaternion.Slerp(fromRotation,toRotation,Mathf.Sin((Amnt - Mathf.Floor(Amnt)) * Mathf.PI));
Where 'TotalTravel' is how long (in seconds) you'd like it to take to do both passes.
NOTE: This is just off the top of my head and the math may not work - just keep the 'percentage' going into the interpolation function between 0 and 1.
The advantage of using 'Sin' like this is that it cycles infinitely anyway, and you get smooth starts and stops to your animation cycle without having to call $$anonymous$$athf.SmoothStep.
Thanks for the info! Your code works just as well if not better than $$anonymous$$e, however I am still running into the same issue as before. The pass in each direction isn't set by an animation. The user clicks on the object to get it to rotate. Is there a way to pass in a stop point in degrees for each direction?
Your answer
Follow this Question
Related Questions
Raycasting at an offset angle? 4 Answers
How to raycast using a vector3 and a rotation? 1 Answer
Convert c# to Js? 1 Answer