- Home /
Smoothing out rotations
Hello. I have a character that is rotating towards the mouse position. The game is played in 2D, but it's in a 3D world similar to Little Big Planet. I got the character rotating towards the mouse, but I wanted to smooth it out and control the rotation speed so it would rotate towards the direction of the mouse rather than rotate exactly towards the mouse all the time. This is where my main problem happens, the way I decided to smooth things out was by taking the angle difference between the mouse/char and then to divide it by rotateSpeed. Then to add that result onto the current rotation, however because it's in quaternions when the mouse moves to the left of the character (which is when the rotation is at 0.7, 0.7) it will instantly jump to -0.7, -0.7 which forces the character to rotate in the opposite direction until it faces the mouse. Does anyone have any ideas for this?
My code is here:
public void RotateSmoothly(GameObject character, Camera mainCamera)
{
Quaternion result;
RaycastHit hit = new RaycastHit();
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
Vector3 characterPosition = character.transform.position;
Vector3 mousePosition = new Vector3();
float tempRotation = new float();
if (Physics.Raycast(ray, out hit))
{
mousePosition = hit.point;
}
tempRotation = Mathf.Atan2((mousePosition.y - characterPosition.y), (mousePosition.x - characterPosition.x)) * Mathf.Rad2Deg;
tempRotation -= 90; // corrects alignment
vectorRotation = new Vector3(-Mathf.Sin(Mathf.Deg2Rad * tempRotation), Mathf.Cos(Mathf.Deg2Rad * tempRotation), 0);
result = Quaternion.AngleAxis(tempRotation, new Vector3(0, 0, 1.0f));
// attempts at smoothing
Quaternion r2 = new Quaternion(result.x / rotateSpeed, result.y / rotateSpeed, result.z / rotateSpeed, result.w / rotateSpeed);
Quaternion r3 = new Quaternion(character.transform.rotation.x + r2.x, character.transform.rotation.y + r2.y, character.transform.rotation.z + r2.z, character.transform.rotation.w + r2.w);
Debug.Log(r3);
character.transform.rotation = r3;
}
I think you need to look into Quaternion.Slerp bud. Also pop any of your camera logic updates/methods into the provided
LateUpdate()
{
}
as this will update after all the other Update methods have fired n all that so it will only change the camera every couple of frames or so- making the movement you should get on the camera (from the Quaternion.Slerp function/method I mentioned to you to look at earlier) smoother atleast. Link to Unity Quaternion.Slerp reference below
Cheers bud, hope this starts your journey to completion :) Gruffy
Answer by RPDEV · Dec 31, 2013 at 11:36 PM
Thanks homie, that's what I was looking for. Didn't know a function for quats existed for that.
Your answer
Follow this Question
Related Questions
Is There An OnMouseStop? 0 Answers
Rotate Player with Camera rotation 2 Answers
Rotating object towards mouse point 1 Answer