3d mouse aim camera 3rd person vertical C#

6.9k views Asked by At

I'm trying to make mouse aim camera that rotate my Player horizontally and vertically, look at Player and keep constant distance. In that version it works fine but I can't make it horizontal also. Each version camera freezes and I rotate my player itself or so. I'm new to programming so I it's propably easy task with proper target.transform.eulerAngles.y assigning also to vertical but I cannot do it.

public class MouseAimCamera : MonoBehaviour {
    public GameObject target;
    public float rotateSpeed = 5;
    Vector3 offset;

    void Start() {
        offset = target.transform.position - transform.position;
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
        target.transform.Rotate(0, horizontal, 0);

        float desiredAngle = target.transform.eulerAngles.y;
        Quaternion rotation = Quaternion.Euler(0, desiredAngle, 0);
        transform.position = target.transform.position - (rotation * offset);

        transform.LookAt(target.transform);
    }
}

I'd be glad if any of you can help me.

1

There are 1 answers

3
Ted Bigham On

This will rotate in world space, which will probably feel wrong at some angles since the camera is not always oriented straight up.

public class MouseAimCamera : MonoBehaviour {
    public GameObject target;
    public float rotateSpeed = 5;

    void Start() {
        transform.parent = target.transform;
        transform.LookAt(target.transform);
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
        float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
        target.transform.RotateAround(target.transform.position, Vector3.up, horizontal);
        target.transform.RotateAround(target.transform.position, Vector3.left, vertical);
    }
}

This will rotate in local space, and might feel more natural depending on what you're trying to build. This is close to your original solution, so i'm guessing it's not what you want.

public class MouseAimCamera : MonoBehaviour {
    public GameObject target;
    public float rotateSpeed = 5;

    void Start() {
        transform.parent = target.transform;
        transform.LookAt(target.transform);
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
        float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
        target.transform.Rotate(vertical, horizontal, 0);
    }
}