简体   繁体   中英

How do I make a camera rotate around a player in 3rd person perspective in Unity?

I am trying to make a camera rotate around the player so that the player is always in the middle of the screen.

I have tried using the Slerp() function.

using UnityEngine;
using System.Collections;


public class rotate : MonoBehaviour
{
    public Transform target;

    public float Speed = 1f;
    public Camera cam;
    public Vector3 offset;
    void Update()
    {
        Vector3 direction = (target.position - cam.transform.position).normalized;


        Quaternion lookrotation = target.rotation;
        Quaternion playerrotation = target.rotation;

        playerrotation.y = target.rotation.y;
        playerrotation.x = 0f;
        playerrotation.z = 0f;

        lookrotation.x = transform.rotation.x;
        lookrotation.z = transform.rotation.z;
        //lookrotation.y = transform.rotation.y;

        offset.x = -target.rotation.x * Mathf.PI;


        transform.rotation = Quaternion.Slerp(transform.rotation, playerrotation, Time.deltaTime * Speed);

        transform.position = Vector3.Slerp(transform.position, target.position + offset, Time.deltaTime * 10000);
    }
}

It worked but the player wasn't in the middle of the screen.

The following script will rotate the gameObject it is attached to so as to keep the Target gameObject in the center of the screen and so that the camera looks in the same direction as the target.

public Transform Target;
public float Speed = 1f;
public Vector3 Offset;
void LateUpdate()
{
    // Compute the position the object will reach
    Vector3 desiredPosition = Target.rotation * (Target.position + Offset);

    // Compute the direction the object will look at
    Vector3 desiredDirection = Vector3.Project( Target.forward, (Target.position - desiredPosition).normalized );

    // Rotate the object
    transform.rotation = Quaternion.Slerp( transform.rotation, Quaternion.LookRotation( desiredDirection ), Time.deltaTime * Speed );

    // Place the object to "compensate" the rotation
    transform.position = Target.position - transform.forward * Offset.magnitude;
}

Note : Never, never, never manipulate the components of a Quaternion unless you really know what you are doing . Quaternions don't store the values you see in the inspector. They are complex entities used to represent rotations, with 4 values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM