[Unity学习] 背景视差因子计算,远近背景移动距离差

    public Camera cam;
    public Transform trans;
    Vector2 startPosiotion;
    float startZ;

    //此物距离trans的z距离
    private float zDistance => transform.position.z - trans.transform.position.z;


    void Start()
    {
        startPosiotion = transform.position;
        startZ = transform.position.z;
    }

    // Update is called once per frame
    void Update()
    {
        // 相机移动距离减初始距离,获取相机偏移距离
        Vector2 camMove = (Vector2)cam.transform.position - startPosiotion;

        //获取人物前还是后,相机前用近裁剪面,后用远裁剪面
        float clippingPlane = cam.transform.position.z + (zDistance > 0 ? cam.farClipPlane : cam.nearClipPlane);

        //计算视差因子
        float parallaxFactor = Mathf.Abs(zDistance) / clippingPlane;

        //获取背景需要偏移的x,y位置
        Vector2 backgroundPos = startPosiotion + camMove * parallaxFactor;

        //因为是2d,所以z不变
        Vector3 newPosition = new Vector3(backgroundPos.x, backgroundPos.y, startZ);

        transform.position = newPosition;
    }

转载至 链接

相关推荐

  1. 【CV】计算机视觉中的特征追踪与背景处理

    2024-06-10 20:46:02       10 阅读
  2. unity专题(1)背景图片的设置

    2024-06-10 20:46:02       17 阅读
  3. SpringCloud 学习笔记 —— 一、背景

    2024-06-10 20:46:02       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-10 20:46:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-10 20:46:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-10 20:46:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-10 20:46:02       18 阅读

热门阅读

  1. PostgreSQL:在CASE WHEN语句中使用SELECT语句

    2024-06-10 20:46:02       13 阅读
  2. fastapi实例

    2024-06-10 20:46:02       12 阅读
  3. 生物神经网络 原理分析研读03

    2024-06-10 20:46:02       11 阅读
  4. 受够了“系统异常”!

    2024-06-10 20:46:02       10 阅读
  5. cell的复用机制和自定义cell

    2024-06-10 20:46:02       12 阅读
  6. Python 函数

    2024-06-10 20:46:02       10 阅读