简体   繁体   中英

Have camera follow player -object position and rotation in 3D-space (Unity3d)

My objective here is to have a smoothed out "follow camera", for my space-fighter proof of concept game. The camera should match roll off the target object in all axis.

To that end I've "stolen" and modified this code from the unity Answers-site, and it works beautifully for X and Y (pitch and yaw), but it refuses to roll.

Code:

public float Distance;
public float Height;
public float RotationDamping;
public GameObject Target;

void LateUpdate()
{
    var wantedRotationAngleYaw = Target.transform.eulerAngles.y;
    var currentRotationAngleYaw = transform.eulerAngles.y;

    var wantedRotationAnglePitch = Target.transform.eulerAngles.x;
    var currentRotationAnglePitch = transform.eulerAngles.x;

    var wantedRotationAngleRoll = Target.transform.eulerAngles.z;
    var currentRotationAngleRoll = transform.eulerAngles.z;

    currentRotationAngleYaw = Mathf.LerpAngle(currentRotationAngleYaw, wantedRotationAngleYaw, RotationDamping * Time.deltaTime);

    currentRotationAnglePitch = Mathf.LerpAngle(currentRotationAnglePitch, wantedRotationAnglePitch, RotationDamping * Time.deltaTime);

    currentRotationAngleRoll = Mathf.LerpAngle(currentRotationAngleRoll, wantedRotationAngleRoll, RotationDamping * Time.deltaTime);

    var currentRotation = Quaternion.Euler(currentRotationAnglePitch, currentRotationAngleYaw, currentRotationAngleRoll);

    transform.position = Target.transform.position;
    transform.position -= currentRotation * Vector3.forward * Distance;

    transform.LookAt(Target.transform);
    transform.position += transform.up * Height;
}

Image:

在此处输入图片说明

I would be more certain about this answer if you explained what you were trying to do, but you should consider moving by Height in the direction of currentRotation * Vector3.up instead of transform.up . Also, consider using currentRotation * Vector3.up to set the local up direction when calling LookAt :

transform.position = Target.transform.position;
transform.position -= currentRotation * Vector3.forward * Distance;

Vector3 currentUp = currentRotation * Vector3.up;
transform.LookAt(Target.transform, currentUp);
transform.position += currentUp * Height;

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