【问题标题】:Make 2D Sprite Face Camera Using Vertex Shader - DirectX 9使用顶点着色器制作 2D Sprite 面部相机 - DirectX 9
【发布时间】:2022-10-02 03:47:58
【问题描述】:

目前,我正在用 C++ 计算世界矩阵,然后将其传递给着色器以使精灵始终面向相机:

static D3DXVECTOR3 up(0, 0, 1);
D3DXMATRIX world, view, proj;

// get the world, view and projection matrix
g_pd3dDevice->GetTransform(D3DTS_WORLD, &world);
g_pd3dDevice->GetTransform(D3DTS_VIEW, &view);
g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &proj);

D3DXMATRIX translation, invView, cameraPosition, rotation,invRotation;

// get the camera position by inversing the view matrix
D3DXMatrixInverse(&invView, NULL, &view);
cameraPosition = D3DXVECTOR3(invView._41, invView._42, invView._43);

// translate the sprite position to a world matrix
D3DXMatrixTranslation(&translation, spritePosition.x, spritePosition.y, spritePosition.z);

// calculate the world matrix rotation to look from
// the sprite position to the camera position
D3DXMatrixLookAtRH(&invRotation, &spritePosition, &cameraPosition, &up);
D3DXMatrixInverse(&rotation, NULL, &invRotation);

// pass the world * view * projection to the shader
world =  rotation * translation;
worldViewProj = matrix.rotation * matrix.view * matrix.proj;

g_pEffect->SetMatrix(\"WorldViewProj\", &worldViewProj);

我最近几天一直在学习 DirectX 和 HLSL,所以我不知道这是否是最佳和正确的方法。 我认为在顶点着色器中会更好,但我不知道如何,请指导我。

  • 请记住,您使用的是旧版 Direct3D 9 和已弃用的 D3DX9 数学库。这意味着您正在使用 20 多年前的 API。请考虑使用 Direct3D 11 作为起点。见Microsoft Docs

标签: c++ matrix directx directx-9


【解决方案1】:

DirectX Tool Kit 中的SimpleMath 包括Matrix::CreateBillboardMatrix::CreateConstrainedBillboard,它们是专门为创建这种变换矩阵而设计的。

inline Matrix Matrix::CreateBillboard(
    const Vector3& object,
    const Vector3& cameraPosition,
    const Vector3& cameraUp,
    const Vector3* cameraForward) noexcept
{
    using namespace DirectX;
    const XMVECTOR O = XMLoadFloat3(&object);
    const XMVECTOR C = XMLoadFloat3(&cameraPosition);
    XMVECTOR Z = XMVectorSubtract(O, C);

    const XMVECTOR N = XMVector3LengthSq(Z);
    if (XMVector3Less(N, g_XMEpsilon))
    {
        if (cameraForward)
        {
            const XMVECTOR F = XMLoadFloat3(cameraForward);
            Z = XMVectorNegate(F);
        }
        else
            Z = g_XMNegIdentityR2;
    }
    else
    {
        Z = XMVector3Normalize(Z);
    }

    const XMVECTOR up = XMLoadFloat3(&cameraUp);
    XMVECTOR X = XMVector3Cross(up, Z);
    X = XMVector3Normalize(X);

    const XMVECTOR Y = XMVector3Cross(Z, X);

    XMMATRIX M;
    M.r[0] = X;
    M.r[1] = Y;
    M.r[2] = Z;
    M.r[3] = XMVectorSetW(O, 1.f);

    Matrix R;
    XMStoreFloat4x4(&R, M);
    return R;
}

这是一个港口XNA游戏工作室使用 DirectXMath 将 C# 数学库转换为 C++。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多