1
\$\begingroup\$

I am creating a character controller where the camera follows the rotation of the player, and allows the user to click and drag to rotate the camera around the player, and lerps back when its released. The part I am struggling with is being able to rotate the camera on both the x and y axes using the Quaternion.AngleAxis method. It gives me the functionality I want on the one axis, but I want to be able to move freely around x and y. I am able to do this when I am not clicking and dragging because I am just lerping the camera to the offset position.

My code is below:

if (Input.GetMouseButton(0))
    {
        Vector2 mouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

        // This only handles rotation around x axis
        currentOffset = Quaternion.AngleAxis (cameraSpeed * mouseInput.x, Vector3.up) * currentOffset;

        Vector3 newPosition = target.position + currentOffset;

        // This is where I am just temporarily setting the y position to look down at the character.
        newPosition.y = target.position.y + 2.0f; 

        transform.position = newPosition;
        transform.LookAt(target);
    }
    else
    {
        Vector3 targetPosition = target.position - target.forward * cameraDistance;
        Vector3 newPosition = transform.position;
        newPosition.x = Mathf.Lerp(newPosition.x, targetPosition.x, 3.0f * Time.deltaTime);
        newPosition.z = Mathf.Lerp(newPosition.z, targetPosition.z, 3.0f * Time.deltaTime);
        transform.position = newPosition;
        transform.LookAt(target);
        currentOffset = transform.position - target.position;
    }  

As you can see I am just temporarily setting the position to 2 units above the target position so the camera slightly looks down at the player. What I would like to do is be able to move both axes to get full observational control around my player. I am not sure if AngleAxis is the right method to be using, but its given me the closest results so far.

\$\endgroup\$
  • 1
    \$\begingroup\$ Is using Quaternion.AngleAxis really a requirement here, or would you be open to solutions that don't use that particular function? There are lots of useful ways to construct and manipulate Quaternions, AngleAxis being just one of them. \$\endgroup\$ – DMGregory Nov 4 '17 at 2:20
  • \$\begingroup\$ Yes 100%, as I mentioned above I am not sure if AngleAxis is the right method to be using, so any other methods that can do something like this work better. \$\endgroup\$ – Kyle Jensen Nov 4 '17 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.