简体   繁体   中英

Unexpected Behavior of a Static Function

I'm working on a DX11 project, and I get an odd behavior with a static function. I'm a little uneducated about static functions, so I'm probably making a mistake somewhere.

My function is simple:

namespace Rendering
{
    static bool PlaceObjectInMatrix(EntityBase* obj, D3DXMATRIX world)
    {

        D3DXMatrixTranslation(&world, obj->GetPosition()->x, obj->GetPosition()->y, obj->GetPosition()->z); 
        return true;
    }
}

and it is called in a loop to render all the objects:

for(unsigned int i = 0; i < listSize; i++)
    {

        if(entities[i].taken == false)
            continue; 
        entities[i].entry->Render(deviceContext, shader);

        PlaceObjectInMatrix(entities[i].entry, worldMatrix);

        if(entities[i].entry->GetIndexCount() != 0) 
        {
            shader->Render(deviceContext, entities[i].entry->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, entities[i].entry->GetTexture(), m_debugLight->GetDirection(), m_debugLight->GetDiffuseColor());
            objectsRendered++;
        }

        d3d->GetWorldMatrix(worldMatrix); //reset world matrix
    }

However, it does not work. When I replace the line with the function call with what is in the function itself, however, it does work. It's like something is getting lost in the function call.

The EntityBase class is abstract, and the class I'm actually rendering with is called EntityModelStatic, which is derived from EntityModel.

static bool PlaceObjectInMatrix(EntityBase* obj, D3DXMATRIX world)

The world argument is passed by value, so the function gets its own copy, and the variable in the caller is not changed. This is likely your problem.

Use a pointer (like D3DXMatrixTranslation ) or a reference, and your problem will likely disappear.

The PlaceObjectInMatrix() function operates on worldMatrix copy. To change the original matrix you must declare the function like this:

static bool PlaceObjectInMatrix(EntityBase* obj, D3DXMATRIX& world);

More conventional way is to use pointers, like this:

static bool PlaceObjectInMatrix(const EntityBase& obj, D3DXMATRIX* world);

This way anyone reading the call code like PlaceObjectInMatrix(*entities[i].entry, &worldMatrix) will realize, that the function will change the worldMatrix object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM