4
\$\begingroup\$

I have a problem, I want my camera to rotate along the Y axis while he is looking at the player with an offset. I want to rotate with Q and E key to right and left around the player but on my Camera Follow Player Script I used Vector3.SmoothDamp to follow the player on the other side when I try to rotate with Keys with transform.RotateAround() it seems like its locked on the Y axis I dont know how to get around this.

Code:


void CameraFollowPlayer()
{
    transform.position = Vector3.SmoothDamp(transform.position, player.position + offset, 
                                             ref velocity, smoothSpeed * Time.deltaTime);
    transform.LookAt(player.position);
}

void RotateRightLeft () 
{
    if(Input.GetKey (KeyCode.E))
    {
        transform.RotateAround(player.position, transform.up, rotateSpeed * Time.deltaTime);
    }

    if(Input.GetKey (KeyCode.Q))
    {
        transform.RotateAround(player.position, -transform.up, rotateSpeed * Time.deltaTime);
    }
}
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Maybe it is because the axis you are passing on RotateAround is your local up (transform.up). You should use Vector3.Up instead if you want to do it on world coordinates, or target's transform.up if you want to rotate around the target's local up normal.

About the offset, you should consider getting a direction vector pointing towards the target, the basic formula is:

d = target - observer

Having that vector, you'll have to normalize it (convert it to a Vector with magnitude of 1) to then multiply it by the desired offset, and finally is just up to assign the camera's position to the target's plus the offset.

A quick example code would be like this:

public class CameraExample : MonoBehaviour
{
    public Transform target;
    public float offset;
    public float rotationSpeed;

    void Update()
    {
        // Follow target at offset:
        transform.position = ((target.position - transform.position).normalized * offset + target.position);

        if(Input.GetKey(KeyCode.E)) transform.RotateAround(target.position, Vector3.up, (rotationSpeed * Time.deltaTime)); // Or transform.up, as I've suggested
        if(Input.GetKey(KeyCode.E)) transform.RotateAround(target.position, Vector3.up, -(rotationSpeed * Time.deltaTime));
    }
}

Hope it helps.

\$\endgroup\$
1
\$\begingroup\$

You could make a target position (a separate transform or Vector3) that rotates at a fixed distance around the player as controlled by key input, then use the SmoothDamp to make the camera gravitate towards that point.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .