简体   繁体   中英

Camera behaviour weird when rotating around player

I am going for a RuneScape-style camera that rotates around the player using WASD . Rotating horizontally works fine but when I mix the two (as in pitching up or down) the camera rotates around the player really awkwardly, the camera might invert or will sort of gimbal I guess.

Here's my code:

public float pitch;
public float zoomSpeed = 4f;
public float minZoom = 5f;
public float maxZoom = 15f;
public Transform target;
public Vector3 offset;
public float yawSpeed = 100f;

private float currentZoom = 10f;
private float currentYaw = 0f;
private float currentPitch = 0f;

void Update()
{
    currentZoom -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
    currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);

    currentYaw -= Input.GetAxis("Horizontal") * yawSpeed * Time.deltaTime;
    currentPitch -= Input.GetAxis("Vertical") * yawSpeed * Time.deltaTime;              

    Debug.Log("Yaw: " + currentYaw + " Pitch: " + currentPitch);
}

void LateUpdate()
{
    transform.position = target.position - offset * currentZoom;
    transform.LookAt(target.position + Vector3.up * pitch);

    transform.RotateAround(target.position, Vector3.up, currentYaw);
    transform.RotateAround(target.position, Vector3.forward, currentPitch); 
}

Any help would be gladly appreciated!

It looks to me that you are using currentPitch, but rotating it around the forward axis? Which would create roll on the world foward axis?

If your up vector is always world up, then the yaw you have will work. But what you want to do is recalculate the right vector from your current location to your target after you apply the yaw.

void LateUpdate() {
    transform.position = target.position - offset * currentZoom;
    transform.LookAt(target.position + Vector3.up * pitch);

    transform.RotateAround(target.position, Vector3.up, currentYaw);
    transform.RotateAround(target.position, Vector3.Cross((target.position - transform.position).normalized, Vector3.up), currentPitch);
}

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