# Rotating object along bezier curve: not rotating enough?

I tried to follow the instructions from the threads on the forum (Cocos2d rotating sprite while moving with CCBezierBy) with Unity, in order to rotate my object as it moves along a bezier curve. But it does not rotate enough, the angle is too low, it goes up to 6 instead of 90 for example, as you can see on this image (the y eulerAngle is at 6, I would expect it to be around 90 with this curve) :

EDIT: here is the solution :

``````Vector3 v3 = newPos - oldPos;
v3.y = 0.0f;
transform.rotation = Quaternion.LookRotation(v3);
``````

Here is the code (in c# with Unity) : (I am comparing x and z to get the angle, and adding the angle to eulerAngles.y so that it rotates around the y axis)

``````void Update () {
if ( Input.GetKey("d") ) start = true;
if ( start ){
myTime = Time.time;
start = false;
}
float theTime = (Time.time - myTime) *0.5f;
if ( theTime < 1 ) {
car.position = Spline.Interp( myArray, theTime );//creates the bezier curve
counterBezier += Time.deltaTime;

//compare 2 positions after 0.1f
if ( counterBezier > 0.1f ){
counterBezier = 0;
cbDone = false;
newpos = car.position;
float angle = Mathf.Atan2(newpos.z - oldpos.z, newpos.x - oldpos.x);
angle += car.eulerAngles.y;
car.eulerAngles = new Vector3(0,angle,0);
}
else if ( counterBezier > 0 && !cbDone ){
oldpos = car.position;
cbDone = true;
}
``````

Thanks

-
It think you're mixing radians and degrees. The result of Mathf.Atan2 is radians. eulerAngles.y is degrees. Everything should be degrees. – Calvin Oct 19 '13 at 23:25
@Calvin thanks, indeed you were right, but the object does not stop rotating with Rad2Deg. Finally it works fine with the code in my edit, thanks for your comment anyway! – Paul Oct 20 '13 at 0:58
Instead of editing the question to add the solution, just post a new answer and mark it as accepted. You may need to wait a bit before you're allowed to. – Sean Middleditch Oct 20 '13 at 1:05

``````Vector3 v3 = newPos - oldPos;
One thing to point out is that `newPos - oldPos` is an approximation of the derivative; if you have a tightly curving bezier, it can be a bad approximation. The exact derivative is calculable in the same way position is. – Drew Cummins Oct 20 '13 at 13:11
It means that you calculate the position by evaluating the bezier function `B` at time `t`: `x = B(t)`. The derivative `d/dt B(t)` is the exact correct direction at time `t`. So instead of calculating the derivative as `v = B(t_now) - B(t_old)` like you are now, you calculate it as `v = d/dt B(t_now)`. – Drew Cummins Oct 21 '13 at 0:05