代码之家  ›  专栏  ›  技术社区  ›  Mr.Pe

将相机与矩形对齐

  •  3
  • Mr.Pe  · 技术社区  · 14 年前

    我们试图对准我们的相机,以便尽可能接近地看到一个矩形(因为我们是在3D中,所以是平行六面体的一个面)。此处考虑的视口的纵横比与要对齐的矩形不匹配。

    我们的工作:

    在我们的场景中是这个矩形。摄像头位于其前方。以下是摄像头的配置:

    projection = Matrix.CreatePerspectiveFieldOfView(
        Fov, AspectRatio, NearPlane, FarPlane
    );
    
    view = Matrix.CreateLookAt(Position, Target, this.Up);
    

    float Fov = PI/4;

    float AspectRatio = device.Viewport.AspectRatio;

    Vector3 Target 设置为矩形的中心。

    Vector3 Position 是我们正在寻找的价值。

    然后初始化相机: oat width=(浮点)GraphicsDevice.Viewport.width; float height=(float)GraphicsDevice.Viewport.height;

    float dist = (width / 2) + (height / 2);
    
    float alpha = 0;
    float beta = 0;
    float gamma = 0;
    
    alpha = (float)Math.Sqrt(Math.Pow(width / 2, 2) + Math.Pow(height / 2, 2));
    beta = height / ((float)Math.Cos(MathHelper.ToRadians(70.3f)) * 2);
    gamma = (float)Math.Sqrt(beta * beta - alpha * alpha);
    
    
    position = new Vector3(width / 2, -height / 2, gamma);
    target = new Vector3(width / 2, -height / 2, dist / 2);
    
    camera = new Camera(GraphicsDevice.Viewport)
    {
        Position = position,
        Target = target,
        Near = 1f,
        Far = 10000f
    };
    

    ( VS solution )

    还有一个精度:为了创建视图,我们使用 Matrix.CreateLookAt 和投影 Matrix.CreatePerspectiveFieldOfView 。我们也不确定这些是否是完美的选择,但听起来不错。

    我们得到的:

    经过一些基本的三角测量,我们得到了一个相机位置,当高度>宽度作为: enter image description here enter image description here

    但是当宽度>高度: enter image description here

    你。。。

    …知道我们做错了什么吗?你有其他更好的方法来实现这一点吗?

    1 回复  |  直到 14 年前
        1
  •  0
  •   alecnash    14 年前

    找金字塔的高度是行不通的。只要使用谭和 Fov = PI/4 代码应该如下所示:

    float tanGamma = (height / 2) * ((float)Math.Tan(MathHelper.ToRadians(67.5f)));