[Unity]带旋转方向的摄像机移动区域限制

2020/04 25 21:04
using UnityEngine;

public class ObliqueCameraBox
{
    private Vector2Int mPoint0; // 左下角
    private Vector2Int mPoint1; // 右上角
    private int mRotation; // 旋转值

    private float mRotationRad
    {
        get
        {
            return Mathf.Deg2Rad * mRotation;
        }
    }

    public ObliqueCameraBox(Vector2Int point0, Vector2Int point1, int rotation)
    {
        mPoint0 = point0;
        mPoint1 = point1;
        mRotation = rotation;
    }
    
    static Vector2 RotateXZ2D(Vector2 point, Vector2 center, float a)
    {
        float x = ( point.x - center.x ) * Mathf.Cos(a) - ( point.y - center.y ) * Mathf.Sin(a) + center.x;
        float z = ( point.x - center.x ) * Mathf.Sin(a) + ( point.y - center.y ) * Mathf.Cos(a) + center.y;
        return new Vector2(x, z);
    }

    public bool Limit(Vector2 input, int damping, ref Vector2 output)
    {
        var p = RotateXZ2D(input, mPoint0, mRotationRad );

        int c = 0;

        if (p.x > mPoint1.x - damping)
        {
            p.x = mPoint1.x - damping; 
        }
        else if (p.x < mPoint0.x + damping)
        {
            p.x = mPoint0.x + damping;
        }
        else
        {
            ++c;
        }

        if (p.y > mPoint1.y - damping)
        {
            p.y = mPoint1.y - damping;
        }
        else if (p.y < mPoint0.y + damping)
        {
            p.y = mPoint0.y + damping;
        }
        else
        {
            ++c;
        }

        if (c == 2)
        {
            return false;
        }
        else
        {
            output = RotateXZ2D(p, mPoint0, -mRotationRad );
            return true;
        }
    }
}

--转载请注明: http://blog.coolcoding.cn/?p=1844

发表回复

欢迎回来 (打开)

(必填)