Problem getting Vector3.Slerp to rotate in the correct direction in specific situation
I am recreating an old project from my highschool days. When trying to rotate the camera to face the proper direction it works fine, except when moving from facing right, to facing backwards. At first I used Mathf.Lerp but ran into the issue of it only rotating the camera clockwise, rather than taking the shortest path. I then flipped over to using Vector3.Slerp because Quaternions are a headache lol. When using vector3.slerp it works properly except when rotating from right to backwards(it goes counterclockwise rather than going clockwise in this situation, when clockwise would be the shortest way to go).
The idea for the project was to take two 80's games and combine their mechanics in a cool way to make a new game. I used Pacman and Mario. At first i used Unity's First Person Controller, but now I am creating my own Player Movement script so that the player can only move in the 4 desired directions- mainly so it is easier to control and more in-line with Pacman. Here is the script(all code that pertains to movement has been commented out):
void Update() { ReadPlayerInput(); }
private void FixedUpdate()
{
ActOnPlayerInputs();
}
public float desiredYrotation;
private void ActOnPlayerInputs()
{
if (moveDir != null)
{
// Vector3 currentMoveDir = (Vector3)moveDir;
// rb.AddForce(currentMoveDir * moveSpeed * Time.deltaTime, ForceMode.Force);
AdjustYRotation(yRotationtoReach);
cameraTransform.eulerAngles = new Vector3(cameraTransform.rotation.x, desiredYrotation, cameraTransform.rotation.z);
}
}
public float yRotationtoReach;
private void AdjustYRotation(float rotationToReach)
{
Vector3 desiredRotation = new Vector3(0,desiredYrotation, 0);
Vector3 reachThisRotation = new Vector3(0,rotationToReach, 0);
Vector3 currentRotation;
currentRotation = Vector3.Slerp(desiredRotation, reachThisRotation, Time.deltaTime);
desiredYrotation = currentRotation.y;
}
private void ReadPlayerInput()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
moveDir = Vector3.left;
yRotationtoReach = 90;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
moveDir = Vector3.right;
yRotationtoReach = 270;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
moveDir = Vector3.forward;
yRotationtoReach = 180;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
moveDir = Vector3.back;
yRotationtoReach = 0;
}
}
Your answer
Follow this Question
Related Questions
Grabbing the Relative eulerAngles.y of a Rotation 1 Answer
Rotate object in 3d space along one axis in the direction of movement vector. 0 Answers
Vector3 and transform.rotation? 2 Answers
Rotating Camera on click and drag 0 Answers
Get LineRenderer positions or perform a transformation to an array of Vector3s 1 Answer