r/Unity3D•
momentum4lyfe

Running into Target lock-on script problem.

Question

So I've made a lock on to target script but I have a problem with constraining the pitch because of Quaternion.LookRotation.

For some reason Quaternion.LookRotation doesn't seem to rotate from the relative rotation, so as you can see in the video the rotation numbers (pitch) doesn't fall in the constraint. Does anyone have any ideas on how to fix this? Cheers.

Video: https://www.youtube.com/watch?v=sM00bYAf_MI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    [Header("Dependencies")]
    public PlayerBase playerBase;

    [Header("Camera Settings")]
    public float mouseSensitivity = 5f;
    public float yaw, pitch;

    Vector2 pitchMinMax = new Vector2(-40, 85);

    public Vector3 currentRotation;
    public Transform PlayerTarget;

    public bool UseMinMax;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = true;
    }

    // Update is called once per frame
    void Update()
    {
        //set pos
        transform.position = playerBase.transform.position + new Vector3(0f, 1.75f, 0);


        if (PlayerTarget != null)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(PlayerTarget.transform.position - transform.position), 5f * Time.deltaTime);
            pitch = transform.localEulerAngles.x;
            yaw = transform.localEulerAngles.y;

        }
        else if (PlayerTarget == null)
        {

            yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
            pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;

            if(UseMinMax)
                pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);

            currentRotation.y = yaw;
            currentRotation.x = pitch;

            transform.localEulerAngles = currentRotation;
        }



    }
}

Video: https://www.youtube.com/watch?v=sM00bYAf_MI

Posted Sep 22, 2019, 4:30 PM UTC

32
Loading comments…