본문 바로가기

프로그램/유니티 스크립트 소스

[유니티 스크립트 소스] 휴대용 카메라

728x90
반응형

휴대용 카메라 소스입니다.

 

using UnityEngine;

public class HandHeldCamera : MonoBehaviour
{
    public Transform m_Target;
    private Rigidbody targetRigidbody;
    public float m_SwaySpeed = .5f;
    public float m_BaseSwayAmount = .5f;
    public float m_TrackingSwayAmount = .5f;
    [Range(-1, 1)] public float m_TrackingBias = 0;
    [SerializeField] public Vector2 m_RotationRange = new Vector2(90, 360);
    [SerializeField] public float m_FollowSpeed = 1;
    
    private Vector3 m_FollowAngles;
    private Quaternion m_OriginalRotation;
    private Vector3 m_FollowVelocity;
    
    void Start()
    {
        if (m_Target == null) return;

        targetRigidbody = m_Target.GetComponent<Rigidbody>();
        m_OriginalRotation = transform.localRotation;
    }

    void LateUpdate()
    {
        FollowTarget(Time.deltaTime);
    }


    void FollowTarget(float deltaTime)
    {
        transform.localRotation = m_OriginalRotation;

        Vector3 localTarget = transform.InverseTransformPoint(m_Target.position);
        float yAngle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;

        yAngle = Mathf.Clamp(yAngle, -m_RotationRange.y * 0.5f, m_RotationRange.y * 0.5f);
        transform.localRotation = m_OriginalRotation * Quaternion.Euler(0, yAngle, 0);

        localTarget = transform.InverseTransformPoint(m_Target.position);
        float xAngle = Mathf.Atan2(localTarget.y, localTarget.z) * Mathf.Rad2Deg;
        xAngle = Mathf.Clamp(xAngle, -m_RotationRange.x * 0.5f, m_RotationRange.x * 0.5f);
        var targetAngles = new Vector3(m_FollowAngles.x + Mathf.DeltaAngle(m_FollowAngles.x, xAngle),
            m_FollowAngles.y + Mathf.DeltaAngle(m_FollowAngles.y, yAngle));

        m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, targetAngles, ref m_FollowVelocity, m_FollowSpeed);
        
        transform.localRotation = m_OriginalRotation * Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0);

        float bx = (Mathf.PerlinNoise(0, Time.time * m_SwaySpeed) - 0.5f);
        float by = (Mathf.PerlinNoise(0, (Time.time * m_SwaySpeed) + 100)) - 0.5f;

        bx *= m_BaseSwayAmount;
        by *= m_BaseSwayAmount;

        float tx = (Mathf.PerlinNoise(0, Time.time * m_SwaySpeed) - 0.5f) + m_TrackingBias;
        float ty = ((Mathf.PerlinNoise(0, (Time.time * m_SwaySpeed) + 100)) - 0.5f) + m_TrackingBias;

        tx *= -m_TrackingSwayAmount * m_FollowVelocity.x;
        ty *= m_TrackingSwayAmount * m_FollowVelocity.y;

        transform.Rotate(bx + tx, by + ty, 0);
    }
}

 

 

 

728x90
반응형