P
P
p4p2019-05-12 06:22:12
Unity
p4p, 2019-05-12 06:22:12

Problem with LookAt object in camera center, how to fix?

I still can't get the desired result. The player has a weapon in his hands, I want it to follow the camera smoothly. The problems start when I look at the player from the front side. I do a rotation constraint and I end up with only the minimum or maximum angle:

lookAtPoint = Application.instance.MainCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 20f));
var rotation = Quaternion.LookRotation(lookAtPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 10);

transform.eulerAngles = new Vector3(ClampAngle(transform.eulerAngles.x, -6, 10), ClampAngle2(transform.eulerAngles.y, 300, 340), 0);

public float ClampAngle(float angle, float min, float max)
        {

            if (angle < 90 || angle > 270)
            {       // if angle in the critic region...
                if (angle > 180) angle -= 360;  // convert all angles to -180..+180
                if (max > 180) max -= 360;
                if (min > 180) min -= 360;
            }
            angle = Mathf.Clamp(angle, min, max);
            if (angle < 0) angle += 360;  // if angle negative, convert to 0..360
            return angle;
        }

        protected float ClampAngle2(float angle, float min, float max)
        {

            angle = NormalizeAngle(angle);
            if (angle > 180)
            {
                angle -= 360;
            }
            else if (angle < -180)
            {
                angle += 360;
            }

            min = NormalizeAngle(min);
            if (min > 180)
            {
                min -= 360;
            }
            else if (min < -180)
            {
                min += 360;
            }

            max = NormalizeAngle(max);
            if (max > 180)
            {
                max -= 360;
            }
            else if (max < -180)
            {
                max += 360;
            }

            // Aim is, convert angles to -180 until 180.
            return Mathf.Clamp(angle, min, max);
        }

        protected float NormalizeAngle(float angle)
        {
            while (angle > 360)
                angle -= 360;
            while (angle < 0)
                angle += 360;
            return angle;
        }

this option works fine when I'm looking from the back, but when I scroll and look from the front - the weapon twitches between the two values.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question